entropy commited on
Commit
bbc7ddf
Β·
verified Β·
1 Parent(s): ad78d17

Upload model

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a πŸ€— transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RZCompressionModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_roberta_zinc_compression_encoder.RZCompressionConfig",
7
+ "AutoModel": "modeling_roberta_zinc_compression_encoder.RZCompressionModel"
8
+ },
9
+ "compression_sizes": [
10
+ 512,
11
+ 256,
12
+ 128,
13
+ 64,
14
+ 32
15
+ ],
16
+ "decoder_cosine_weight": 1.0,
17
+ "decoder_layers": 4,
18
+ "dropout": 0.1,
19
+ "encoder_layers": 4,
20
+ "input_size": 768,
21
+ "layer_norm_eps": 1e-12,
22
+ "model_type": "roberta_zinc_compression_encoder",
23
+ "mse_loss_weight": 0.0,
24
+ "pearson_loss_weight": 1.0,
25
+ "topk_values": [
26
+ 10,
27
+ 100,
28
+ 256
29
+ ],
30
+ "torch_dtype": "float32",
31
+ "transformers_version": "4.51.3"
32
+ }
configuration_roberta_zinc_compression_encoder.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class RZCompressionConfig(PretrainedConfig):
6
+ """
7
+ Configuration for the roberta_zinc embedding-compression models.
8
+
9
+ Args:
10
+ input_size (int): Dimension of the input embedding.
11
+ compression_sizes (List[int]): One or more output dimensions.
12
+ encoder_layers (int): Number of FeedForwardLayers in the encoder path.
13
+ decoder_layers (int): Number of FeedForwardLayers in the optional decoder.
14
+ dropout (float): Drop-out prob in every layer except the final ones.
15
+ layer_norm_eps (float | None): Epsilon for LayerNorm.
16
+ mse_loss_weight (float): Weight for MSE loss on base-to-compressed similarity matrices
17
+ pearson_loss_weight (float): Weight for Pearson loss on base-to-compressed similarity matrices
18
+ topk_values (List[int]): Top-k values for weighting mse/pearson loss
19
+ decoder_cosine_weight (float): weight for decoder cosine similarity loss
20
+ """
21
+ model_type = "roberta_zinc_compression_encoder"
22
+
23
+ def __init__(
24
+ self,
25
+ # ── model params ─────────────────────────────────────────────
26
+ input_size: int = 768,
27
+ compression_sizes: List[int] = (32, 64, 128, 256, 512),
28
+ encoder_layers: int = 2,
29
+ decoder_layers: int = 2,
30
+ dropout: float = 0.1,
31
+ layer_norm_eps: Optional[float] = 1e-12,
32
+ # ── loss knobs ───────────────────────────────────────────────
33
+ mse_loss_weight: float = 0.0,
34
+ pearson_loss_weight: float = 0.0,
35
+ topk_values: list[int] = (10, 100),
36
+ decoder_cosine_weight: float = 0.0,
37
+ **kwargs,
38
+ ):
39
+ self.input_size = input_size
40
+ self.compression_sizes = list(compression_sizes)
41
+ self.encoder_layers = encoder_layers
42
+ self.decoder_layers = decoder_layers
43
+ self.dropout = dropout
44
+ self.layer_norm_eps = layer_norm_eps
45
+ self.mse_loss_weight = mse_loss_weight
46
+ self.topk_values = topk_values
47
+ self.pearson_loss_weight = pearson_loss_weight
48
+ self.decoder_cosine_weight = decoder_cosine_weight
49
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:faa111596c4d62aba81b98d0f33579d7a886a2b931a72d943b28331f4c42e886
3
+ size 244378384
modeling_roberta_zinc_compression_encoder.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from dataclasses import dataclass
5
+ from typing import Dict, List, Optional, Tuple
6
+
7
+ from transformers import PreTrainedModel
8
+ from transformers.utils import ModelOutput
9
+
10
+ from .configuration_roberta_zinc_compression_encoder import RZCompressionConfig
11
+
12
+ # pairwise cosine ----------------------------------------------------------------
13
+ def pairwise_cosine(x: torch.Tensor) -> torch.Tensor:
14
+ x = F.normalize(x, p=2, dim=-1)
15
+ return x @ x.t() # [B, B]
16
+
17
+ # remove diagonal -----------------------------------------------------------------
18
+ def drop_diag(M: torch.Tensor) -> torch.Tensor:
19
+ n = M.size(0)
20
+ return M.masked_select(~torch.eye(n, dtype=torch.bool, device=M.device)).view(n, n - 1)
21
+
22
+ # pearson row-wise ----------------------------------------------------------------
23
+ def rowwise_pearson(ref: torch.Tensor, comp: torch.Tensor, rm_diag: bool=True) -> torch.Tensor:
24
+ if rm_diag:
25
+ ref = drop_diag(ref)
26
+ comp = drop_diag(comp)
27
+ ref_z = F.normalize(ref - ref.mean(dim=1, keepdim=True), p=2, dim=1)
28
+ cmp_z = F.normalize(comp - comp.mean(dim=1, keepdim=True), p=2, dim=1)
29
+ return 1 - (ref_z * cmp_z).sum(dim=1).mean() # 0 = perfect corr
30
+
31
+ # aggregate loss ------------------------------------------------------------------
32
+ def compute_losses(
33
+ embedding: torch.Tensor, # (batch_size, d)
34
+ compressed: Dict[int, torch.Tensor], # Dict[size, (batch_size, size)]
35
+ recon_stack: torch.Tensor | None, # (batch_size, n_heads, d)
36
+ cfg,
37
+ ) -> tuple[torch.Tensor, dict[str, float]]:
38
+ """Return (total_loss, terms_dict)"""
39
+ device = embedding.device
40
+ loss_total = torch.zeros((), device=device)
41
+ terms: dict[str, float] = {}
42
+
43
+ # ---- base similarities (detach to save mem) ---------------------------
44
+ with torch.no_grad():
45
+ base_sims = pairwise_cosine(embedding)
46
+ ranks = base_sims.argsort(-1, descending=True)
47
+
48
+ # ======================================================================
49
+ # 1) encoder / compressed losses
50
+ # ======================================================================
51
+ for size, z in compressed.items():
52
+ tag = f"cmp{size}"
53
+ comp_sims = pairwise_cosine(z)
54
+
55
+ # plain MSE --------------------------------------------------------
56
+ if cfg.mse_loss_weight:
57
+ mse = F.mse_loss(drop_diag(base_sims), drop_diag(comp_sims))
58
+ loss_total += cfg.mse_loss_weight * mse
59
+ terms[f"{tag}_mse"] = mse.detach()
60
+
61
+ # top-k MSE --------------------------------------------------------
62
+ if cfg.mse_loss_weight and cfg.topk_values:
63
+ tk_vals = []
64
+ for k in cfg.topk_values:
65
+ idx = ranks[:, 1 : k + 1]
66
+ ref_k = torch.gather(base_sims, 1, idx)
67
+ cmp_k = torch.gather(comp_sims, 1, idx)
68
+ tk_mse = F.mse_loss(ref_k, cmp_k)
69
+ tk_vals.append(tk_mse)
70
+ terms[f"{tag}_top{k}"] = tk_mse.detach()
71
+ tk_agg = torch.stack(tk_vals).mean()
72
+ loss_total += cfg.topk_mse_loss_weight * tk_agg
73
+ terms[f"{tag}_topk_mean"] = tk_agg.detach()
74
+
75
+ # Pearson ----------------------------------------------------------
76
+ if cfg.pearson_loss_weight:
77
+ pr = rowwise_pearson(base_sims, comp_sims)
78
+ loss_total += cfg.pearson_loss_weight * pr
79
+ terms[f"{tag}_pearson"] = pr.detach()
80
+
81
+ if cfg.pearson_loss_weight and cfg.topk_values:
82
+ pr_vals = []
83
+ for k in cfg.topk_values:
84
+ idx = ranks[:, 1 : k + 1]
85
+ ref_k = torch.gather(base_sims, 1, idx)
86
+ cmp_k = torch.gather(comp_sims, 1, idx)
87
+ pr = rowwise_pearson(ref_k, cmp_k, rm_diag=False)
88
+ pr_vals.append(pr)
89
+ terms[f"{tag}_pearson_top{k}"] = pr.detach()
90
+ pr_agg = torch.stack(pr_vals).sum()
91
+ loss_total += cfg.pearson_loss_weight * pr_agg
92
+
93
+ # ======================================================================
94
+ # 2) decoder losses
95
+ # ======================================================================
96
+ if recon_stack is not None:
97
+ # cosine -----------------------------------------------------------
98
+ if cfg.decoder_cosine_weight:
99
+ cos_loss = 1 - F.cosine_similarity(
100
+ recon_stack,
101
+ embedding.unsqueeze(1).expand_as(recon_stack),
102
+ dim=-1,
103
+ ).mean()
104
+ loss_total += cfg.decoder_cosine_weight * cos_loss
105
+ terms["dec_cosine"] = cos_loss.detach()
106
+
107
+ return loss_total, terms
108
+
109
+
110
+ # ─── basic blocks ───────────────────────────────────────────────
111
+ class FeedForward(nn.Module):
112
+ def __init__(self, d_in: int, d_out: int):
113
+ super().__init__()
114
+ self.fc1 = nn.Linear(d_in, d_out * 2)
115
+ self.fc2 = nn.Linear(d_out, d_out)
116
+
117
+ def forward(self, x):
118
+ x = self.fc1(x)
119
+ x1, x2 = x.chunk(2, dim=-1)
120
+ return self.fc2(F.silu(x1) * x2)
121
+
122
+ class FeedForwardLayer(nn.Module):
123
+ def __init__(
124
+ self, d_in: int, d_out: int, dropout: float = 0.1, layer_norm_eps: Optional[float] = 1e-12
125
+ ):
126
+ super().__init__()
127
+ self.ff = FeedForward(d_in, d_out)
128
+ self.skip = nn.Linear(d_in, d_out) if d_in != d_out else nn.Identity()
129
+ self.dropout = nn.Dropout(dropout)
130
+ self.norm = (
131
+ nn.LayerNorm(d_out, eps=layer_norm_eps)
132
+ if layer_norm_eps is not None else nn.Identity()
133
+ )
134
+
135
+ def forward(self, x):
136
+ y = self.ff(self.dropout(x)) + self.skip(x)
137
+ return self.norm(y)
138
+
139
+
140
+ # ─── pure PyTorch compressor ────────────────────────────────────
141
+ class CompressionModel(nn.Module):
142
+ """
143
+ Encoder β†’ (optional) Decoder.
144
+ """
145
+
146
+ def __init__(
147
+ self,
148
+ d_in: int,
149
+ d_comp: int,
150
+ encoder_layers: int,
151
+ decoder_layers: int,
152
+ dropout: float,
153
+ layer_norm_eps: Optional[float],
154
+ ):
155
+ super().__init__()
156
+
157
+ enc_layers: List[nn.Module] = []
158
+ for i in range(encoder_layers):
159
+ last = i == encoder_layers - 1
160
+ enc_layers.append(
161
+ FeedForwardLayer(
162
+ d_in,
163
+ d_comp if last else d_in,
164
+ dropout if not last else 0.0,
165
+ None if last else layer_norm_eps,
166
+ )
167
+ )
168
+ self.encoder = nn.Sequential(*enc_layers)
169
+
170
+ # optional decoder
171
+ dec_layers: List[nn.Module] = []
172
+ for i in range(decoder_layers):
173
+ last = i == decoder_layers - 1
174
+ d_prev = d_comp if i==0 else d_in
175
+ dec_layers.append(
176
+ FeedForwardLayer(
177
+ d_prev,
178
+ d_in,
179
+ dropout if not last else 0.0,
180
+ None if last else layer_norm_eps,
181
+ )
182
+ )
183
+ self.decoder = nn.Sequential(*dec_layers) if dec_layers else None
184
+
185
+ def forward(self, x) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
186
+ z = self.encoder(x)
187
+ x_recon = self.decoder(z) if self.decoder is not None else None
188
+ return z, x_recon
189
+
190
+
191
+ # ─── HF wrapper ─────────────────────────────────────────────────
192
+ @dataclass
193
+ class RZCompressionOutput(ModelOutput):
194
+ loss: torch.FloatTensor
195
+ loss_terms: Dict[str, torch.Tensor] | None = None
196
+ compressed: Dict[int, torch.FloatTensor] | None = None
197
+ reconstructed: torch.FloatTensor | None = None
198
+
199
+ class RZCompressionModel(PreTrainedModel):
200
+ config_class = RZCompressionConfig
201
+
202
+ def __init__(self, config: RZCompressionConfig):
203
+ super().__init__(config)
204
+
205
+ self.compressors = nn.ModuleDict(
206
+ {
207
+ str(size): CompressionModel(
208
+ d_in=config.input_size,
209
+ d_comp=size,
210
+ encoder_layers=config.encoder_layers,
211
+ decoder_layers=config.decoder_layers,
212
+ dropout=config.dropout,
213
+ layer_norm_eps=config.layer_norm_eps,
214
+ )
215
+ for size in config.compression_sizes
216
+ }
217
+ )
218
+
219
+ self.post_init()
220
+
221
+ def get_encoders(self, unpack_single=False):
222
+ encoders = {}
223
+ for k,v in self.compressors.items():
224
+ v = v.encoder
225
+ if len(v)==1 and unpack_single:
226
+ # unpack from nn.Sequential if only a single layer
227
+ v = v[0]
228
+ encoders[k] = v
229
+ encoders = nn.ModuleDict(encoders)
230
+ return encoders
231
+
232
+ def save_encoders(self, path, unpack_single=False):
233
+ encoders = self.get_encoders(unpack_single)
234
+ torch.save(encoders.state_dict(), path)
235
+
236
+ def compress(self,
237
+ inputs: torch.Tensor,
238
+ compression_sizes: List[int]):
239
+ compressed = {d: self.compressors[str(d)].encoder(inputs) for d in compression_sizes}
240
+ return compressed
241
+
242
+ def forward(self, embedding, return_dict=True, compute_loss=True):
243
+ # ---------- forward passes ------------------------------------------------
244
+ compressed, recons = {}, []
245
+ for size, module in self.compressors.items():
246
+ z, rec = module(embedding)
247
+ compressed[int(size)] = z
248
+ if rec is not None:
249
+ recons.append(rec)
250
+ recon_stack = torch.stack(recons, dim=1) if recons else None
251
+
252
+ # ---------- losses --------------------------------------------------------
253
+ if compute_loss:
254
+ loss_total, terms = compute_losses(embedding, compressed, recon_stack, self.config)
255
+ else:
256
+ loss_total, terms = torch.zeros((), device=embedding.device), {}
257
+
258
+ if not return_dict:
259
+ return compressed, recon_stack, loss_total, terms
260
+
261
+ return RZCompressionOutput(
262
+ loss=loss_total,
263
+ loss_terms=terms,
264
+ compressed=compressed,
265
+ reconstructed=recon_stack,
266
+ )