omarSorour123 commited on
Commit
6030462
Β·
verified Β·
1 Parent(s): 1ae5b94

Uploaded dataset from Kaggle

Browse files
.virtual_documents/__notebook_source__.ipynb ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modeling_lfm2_bi.py
3
+ -------------------
4
+ Bidirectional LFM2 model for encoder tasks (MNTP, NER, RE).
5
+
6
+ components:
7
+ - Lfm2BiModel: backbone with bidirectional attention + symmetric convolutions
8
+
9
+ Bug fixes over original submission:
10
+ 1. CUDA fast path (causal_conv1d_fn) bypassed via forward() override
11
+ 2. from_pretrained loads causal LM weights cleanly (no double conversion)
12
+ 3. Proper 4D attention mask construction for GQA layers
13
+ """
14
+
15
+ import types
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from transformers import AutoConfig
20
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
21
+ from transformers.models.lfm2.modeling_lfm2 import (
22
+ Lfm2ForCausalLM,
23
+ Lfm2Model,
24
+ Lfm2PreTrainedModel,
25
+ Lfm2ShortConv,
26
+ )
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Core conversion: causal conv β†’ bidirectional conv
31
+ # ---------------------------------------------------------------------------
32
+
33
+ def _make_conv_bidirectional(conv_module: Lfm2ShortConv) -> None:
34
+ """
35
+ Convert a single Lfm2ShortConv layer to bidirectional in-place.
36
+
37
+ How the original causal conv works (confirmed from source):
38
+ self.conv = nn.Conv1d(..., padding=L_cache-1) # left-only padding
39
+ conv_out = self.conv(Bx)[..., :seqlen] # trim excess right tokens
40
+
41
+ For kernel_size=4 (LFM2-350M), original padding=3:
42
+ output_len = T + 2*3 - 4 + 1 = T + 3 β†’ [:T] = T βœ“ (causal left-only)
43
+
44
+ Bidirectional fix β€” replace with symmetric padding=kernel_size//2=2:
45
+ output_len = T + 2*2 - 4 + 1 = T + 1 β†’ [:T] = T βœ“ (center-padded)
46
+
47
+ Critical: override forward() to always call slow_forward().
48
+ Without this, CUDA path calls causal_conv1d_fn and ignores self.conv entirely.
49
+ """
50
+ kernel_size = conv_module.L_cache # == config.conv_L_cache (4 for LFM2-350M)
51
+ old_conv = conv_module.conv
52
+
53
+ # Replace conv with symmetric padding version, copy pretrained weights
54
+ new_conv = nn.Conv1d(
55
+ in_channels=old_conv.in_channels,
56
+ out_channels=old_conv.out_channels,
57
+ kernel_size=kernel_size,
58
+ groups=old_conv.groups,
59
+ bias=old_conv.bias is not None,
60
+ padding=kernel_size // 2, # symmetric: equal left and right context
61
+ )
62
+ new_conv.weight.data.copy_(old_conv.weight.data)
63
+ if old_conv.bias is not None:
64
+ new_conv.bias.data.copy_(old_conv.bias.data)
65
+
66
+ conv_module.conv = new_conv
67
+
68
+ # Override forward to bypass causal CUDA kernel (causal_conv1d_fn).
69
+ # slow_forward calls self.conv which is now the symmetric version.
70
+ def _bidirectional_forward(
71
+ self,
72
+ hidden_states: torch.Tensor,
73
+ past_key_values=None,
74
+ cache_position=None,
75
+ attention_mask=None,
76
+ **kwargs,
77
+ ) -> torch.Tensor:
78
+ # Force slow_forward β€” never causal_conv1d_fn
79
+ return self.slow_forward(
80
+ hidden_states,
81
+ past_key_values=None, # no caching during encoding
82
+ cache_position=cache_position,
83
+ attention_mask=attention_mask,
84
+ )
85
+
86
+ conv_module.forward = types.MethodType(_bidirectional_forward, conv_module)
87
+
88
+
89
+ # ---------------------------------------------------------------------------
90
+ # Bidirectional backbone
91
+ # ---------------------------------------------------------------------------
92
+
93
+ class Lfm2BiModel(Lfm2Model):
94
+ """
95
+ LFM2 backbone converted to bidirectional operation.
96
+
97
+ Changes vs Lfm2Model:
98
+ - GQA layers: full 4D attention mask (no causal triangular mask)
99
+ - Conv layers: symmetric padding + slow_forward forced (via _make_conv_bidirectional)
100
+
101
+ State dict keys are identical to Lfm2Model for clean weight loading.
102
+ """
103
+
104
+ def __init__(self, config):
105
+ super().__init__(config)
106
+ # Do NOT call _make_bidirectional here β€” weights are random at init.
107
+ # It is called in from_pretrained after weights are loaded.
108
+
109
+ def _make_bidirectional(self) -> None:
110
+ """Convert all conv and attention layers in-place."""
111
+ converted_conv = 0
112
+ for layer in self.layers:
113
+ # 1. Convert convolutions
114
+ if not layer.is_attention_layer and hasattr(layer, "conv"):
115
+ _make_conv_bidirectional(layer.conv)
116
+ converted_conv += 1
117
+
118
+ # 2. Safety check: Ensure attention blocks don't force causal behavior
119
+ elif layer.is_attention_layer and hasattr(layer, "attn"):
120
+ # If your inspection shows an internal 'is_causal' attribute, kill it here:
121
+ if hasattr(layer.attn, "is_causal"):
122
+ layer.attn.is_causal = False
123
+
124
+ print(f"[Lfm2BiModel] Converted {converted_conv} conv layers. Attention maps unconstrained.")
125
+
126
+ @classmethod
127
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
128
+ """
129
+ Load pretrained Lfm2Model weights then apply bidirectional conversion.
130
+
131
+ Clean flow:
132
+ 1. Load into standard Lfm2Model (causal) to get pretrained weights
133
+ 2. Transfer weights to Lfm2BiModel instance
134
+ 3. Apply _make_bidirectional() exactly once
135
+ """
136
+ config = kwargs.pop("config", None)
137
+ if config is None:
138
+ config = AutoConfig.from_pretrained(
139
+ pretrained_model_name_or_path, **{
140
+ k: v for k, v in kwargs.items()
141
+ if k in ("trust_remote_code", "revision", "cache_dir")
142
+ }
143
+ )
144
+
145
+ # Load causal model with pretrained weights
146
+ base = Lfm2Model.from_pretrained(
147
+ pretrained_model_name_or_path, *model_args, config=config, **kwargs
148
+ )
149
+
150
+ # Build bidirectional instance and transfer weights
151
+ # Use __new__ + parent __init__ to avoid calling _make_bidirectional prematurely
152
+ instance = cls.__new__(cls)
153
+ Lfm2Model.__init__(instance, config)
154
+ instance.load_state_dict(base.state_dict(), strict=True)
155
+
156
+ del base # free causal model memory
157
+
158
+ # Apply bidirectional conversion once with pretrained weights in place
159
+ instance._make_bidirectional()
160
+
161
+ return instance
162
+
163
+ def forward(
164
+ self,
165
+ input_ids: torch.LongTensor = None,
166
+ attention_mask: torch.Tensor = None,
167
+ position_ids: torch.LongTensor = None,
168
+ inputs_embeds: torch.Tensor = None,
169
+ output_hidden_states: bool = False,
170
+ return_dict: bool = True,
171
+ **kwargs,
172
+ ) -> BaseModelOutput:
173
+ # Drop generation-only kwargs
174
+ kwargs.pop("past_key_values", None)
175
+ kwargs.pop("use_cache", None)
176
+ kwargs.pop("cache_position", None)
177
+
178
+ if inputs_embeds is None:
179
+ inputs_embeds = self.embed_tokens(input_ids)
180
+
181
+ batch_size, seq_len, _ = inputs_embeds.shape
182
+ device = inputs_embeds.device
183
+
184
+ # Position ids: full sequence, no offset
185
+ cache_position = torch.arange(seq_len, device=device)
186
+ if position_ids is None:
187
+ position_ids = cache_position.unsqueeze(0).expand(batch_size, -1)
188
+
189
+ # --- Attention mask for GQA layers (4D additive) ---
190
+ # Shape: (B, 1, T, T) β€” 0 = attend, -inf = ignore
191
+ if attention_mask is not None and attention_mask.dim() == 2:
192
+ # (B, T) binary mask β†’ (B, 1, T, T) additive mask
193
+ # Key mask: which keys to ignore
194
+ key_mask = attention_mask[:, None, None, :].expand(
195
+ batch_size, 1, seq_len, seq_len
196
+ ) # 1 = keep, 0 = pad
197
+ # Query mask: ignore rows where query is padding
198
+ query_mask = attention_mask[:, :, None, None].expand(
199
+ batch_size, seq_len, 1, seq_len # will broadcast
200
+ )
201
+ # Combined: only attend where both query and key are real tokens
202
+ combined = (key_mask * query_mask.transpose(1, 2)).to(inputs_embeds.dtype)
203
+ # Convert to additive: 0 β†’ 0.0 (attend), 1 β†’ min_val (ignore)... wait
204
+ # 1 means real token (attend), 0 means pad (ignore)
205
+ # Additive: real=0.0, pad=very_negative
206
+ bi_attn_mask = (1.0 - combined) * torch.finfo(inputs_embeds.dtype).min
207
+
208
+ # Linear mask for conv layers: 2D binary (B, T)
209
+ linear_mask = attention_mask
210
+ elif attention_mask is not None:
211
+ # Already in 4D or other format, use as-is
212
+ bi_attn_mask = attention_mask
213
+ linear_mask = None
214
+ else:
215
+ bi_attn_mask = None
216
+ linear_mask = None
217
+
218
+ # --- Forward through layers ---
219
+ hidden_states = inputs_embeds
220
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
221
+
222
+ all_hidden_states = (hidden_states,) if output_hidden_states else None
223
+
224
+ for layer in self.layers[:self.config.num_hidden_layers]:
225
+ # GQA layers get 4D mask, conv layers get 2D binary mask
226
+ layer_mask = bi_attn_mask if layer.is_attention_layer else linear_mask
227
+
228
+ hidden_states = layer(
229
+ hidden_states,
230
+ attention_mask=layer_mask,
231
+ position_embeddings=position_embeddings,
232
+ position_ids=position_ids,
233
+ past_key_values=None,
234
+ cache_position=cache_position,
235
+ )
236
+
237
+ if output_hidden_states:
238
+ all_hidden_states = all_hidden_states + (hidden_states,)
239
+
240
+ hidden_states = self.embedding_norm(hidden_states)
241
+
242
+ return BaseModelOutput(
243
+ last_hidden_state=hidden_states,
244
+ hidden_states=all_hidden_states,
245
+ )
246
+
247
+
248
+
249
+ class Lfm2BiForCausalLM(Lfm2ForCausalLM):
250
+ """
251
+ Causal LM wrapper that patches the underlying Lfm2Model backbone
252
+ with your bidirectional Lfm2BiModel for MNTP training.
253
+ """
254
+ @classmethod
255
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
256
+ # 1. Load the original causal model (brings in backbone + lm_head weights)
257
+ model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
258
+
259
+ # 2. Dynamically change the backbone class to your bidirectional version
260
+ model.model.__class__ = Lfm2BiModel
261
+
262
+ # 3. Execute your in-place conv transformations
263
+ model.model._make_bidirectional()
264
+
265
+ return model
266
+
267
+
268
+
269
+
270
+ # Spoof the module paths so Hugging Face can find a physical __file__
271
+ Lfm2BiModel.__module__ = Lfm2Model.__module__
272
+
273
+ # Do the same for your CausalLM wrapper if you're using Phase 1
274
+ if 'Lfm2BiForCausalLM' in globals():
275
+ Lfm2BiForCausalLM.__module__ = Lfm2ForCausalLM.__module__
276
+ model = Lfm2BiModel.from_pretrained("LiquidAI/LFM2.5-350M")
277
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
278
+
279
+ # Load config to grab its class mapping
280
+ config = AutoConfig.from_pretrained("LiquidAI/LFM2.5-350M") # or your specific model path
281
+ config_class = type(config)
282
+
283
+
284
+ AutoModel.register(config_class, Lfm2BiModel, exist_ok=True)
285
+ AutoModelForCausalLM.register(config_class, Lfm2BiForCausalLM, exist_ok=True)
286
+
287
+
288
+
289
+
290
+
291
+ from transformers import Lfm2ForCausalLM
292
+
293
+
294
+
295
+
296
+ config =
297
+
298
+
299
+
300
+
301
+
302
+ import json
303
+
304
+ mntp_config = {
305
+ "model_name_or_path": "LiquidAI/LFM2.5-350M",
306
+ "dataset_name": "wikitext",
307
+ "dataset_config_name": "wikitext-103-raw-v1",
308
+ "per_device_train_batch_size": 8,
309
+ "per_device_eval_batch_size": 8,
310
+ "gradient_accumulation_steps": 4,
311
+ "do_train": True,
312
+ "do_eval": True,
313
+ "max_seq_length": 512,
314
+ "mask_token_type": "blank",
315
+ "data_collator_type": "all_mask",
316
+ "mlm_probability": 0.15,
317
+ "overwrite_output_dir": True,
318
+ "output_dir": "output/LFM2.5-350M-MNTP",
319
+ "evaluation_strategy": "steps",
320
+ "eval_steps": 100,
321
+ "save_steps": 200,
322
+ "stop_after_n_steps": 1000,
323
+ "lora_r": 16,
324
+ "gradient_checkpointing": True,
325
+ "torch_dtype": "bfloat16",
326
+ "trust_remote_code": True
327
+ }
328
+
329
+ with open("mntp_config.json", "w") as f:
330
+ json.dump(mntp_config, f, indent=4)
331
+
332
+ print("Successfully generated mntp_config.json in workspace.")
333
+
334
+
335
+ script_content = """import types
336
+ import sys
337
+ import os
338
+ import torch
339
+ import torch.nn as nn
340
+
341
+ # ===========================================================================
342
+ # 0. BACKWARD COMPATIBILITY MONKEYPATCH (Fixes llm2vec TPU import error)
343
+ # ===========================================================================
344
+ import transformers
345
+ if not hasattr(transformers, "is_torch_tpu_available"):
346
+ # Injects a dummy fallback function since newer transformers removed it from root.
347
+ # Safe for GPU/CPU environments.
348
+ transformers.is_torch_tpu_available = lambda *args, **kwargs: False
349
+
350
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
351
+ from transformers.modeling_outputs import BaseModelOutput
352
+
353
+ # Dynamically locate the experiments directory based on your workspace layout
354
+ if os.path.exists("./experiments"):
355
+ sys.path.append(os.path.abspath("./experiments"))
356
+ elif os.path.exists("./llm2vec/experiments"):
357
+ sys.path.append(os.path.abspath("./llm2vec/experiments"))
358
+ else:
359
+ raise FileNotFoundError("Could not find the llm2vec 'experiments' directory in your workspace.")
360
+
361
+ import run_mntp
362
+
363
+ # ===========================================================================
364
+ # 1. DYNAMIC CLASS EXTRACTION
365
+ # ===========================================================================
366
+ print("[Launcher] Fetching base model blueprint to dynamically extract remote code architectures...")
367
+ try:
368
+ base_dummy = AutoModelForCausalLM.from_pretrained(
369
+ "LiquidAI/LFM2.5-350M",
370
+ trust_remote_code=True,
371
+ torch_dtype=torch.bfloat16
372
+ )
373
+ Lfm2ForCausalLM = base_dummy.__class__
374
+ Lfm2Model = base_dummy.model.__class__
375
+
376
+ Lfm2ShortConv = None
377
+ for layer in base_dummy.model.layers:
378
+ if hasattr(layer, "conv"):
379
+ Lfm2ShortConv = layer.conv.__class__
380
+ break
381
+
382
+ if Lfm2ShortConv is None:
383
+ raise AttributeError("Could not dynamically trace Lfm2ShortConv from architecture layers.")
384
+
385
+ print(f"[Launcher] Safely extracted classes: {Lfm2ForCausalLM.__name__}, {Lfm2Model.__name__}")
386
+
387
+ del base_dummy
388
+ torch.cuda.empty_cache()
389
+ except Exception as e:
390
+ print(f"[Launcher] Fallback failed during runtime reflection setup: {e}")
391
+ raise e
392
+
393
+ # ===========================================================================
394
+ # 2. CORE BIDIRECTIONAL CONVERSION ENGINE
395
+ # ===========================================================================
396
+
397
+ def _make_conv_bidirectional(conv_module: Lfm2ShortConv) -> None:
398
+ kernel_size = conv_module.L_cache
399
+ old_conv = conv_module.conv
400
+
401
+ new_conv = nn.Conv1d(
402
+ in_channels=old_conv.in_channels,
403
+ out_channels=old_conv.out_channels,
404
+ kernel_size=kernel_size,
405
+ groups=old_conv.groups,
406
+ bias=old_conv.bias is not None,
407
+ padding=kernel_size // 2,
408
+ )
409
+ new_conv.weight.data.copy_(old_conv.weight.data)
410
+ if old_conv.bias is not None:
411
+ new_conv.bias.data.copy_(old_conv.bias.data)
412
+
413
+ conv_module.conv = new_conv
414
+
415
+ def _bidirectional_forward(
416
+ self,
417
+ hidden_states: torch.Tensor,
418
+ past_key_values=None,
419
+ cache_position=None,
420
+ attention_mask=None,
421
+ **kwargs,
422
+ ) -> torch.Tensor:
423
+ return self.slow_forward(
424
+ hidden_states,
425
+ past_key_values=None,
426
+ cache_position=cache_position,
427
+ attention_mask=attention_mask,
428
+ )
429
+
430
+ conv_module.forward = types.MethodType(_bidirectional_forward, conv_module)
431
+
432
+
433
+ # ===========================================================================
434
+ # 3. BIDIRECTIONAL MODEL BACKBONE DEFINITIONS
435
+ # ===========================================================================
436
+
437
+ class Lfm2BiModel(Lfm2Model):
438
+ def __init__(self, config):
439
+ super().__init__(config)
440
+
441
+ def _make_bidirectional(self) -> None:
442
+ converted_conv = 0
443
+ for layer in self.layers:
444
+ if not layer.is_attention_layer and hasattr(layer, "conv"):
445
+ _make_conv_bidirectional(layer.conv)
446
+ converted_conv += 1
447
+ elif layer.is_attention_layer and hasattr(layer, "attn"):
448
+ if hasattr(layer.attn, "is_causal"):
449
+ layer.attn.is_causal = False
450
+ print(f"[Lfm2BiModel] Applied modifications across {converted_conv} conv layers.")
451
+
452
+ @classmethod
453
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
454
+ config = kwargs.pop("config", None)
455
+ if config is None:
456
+ config = AutoConfig.from_pretrained(
457
+ pretrained_model_name_or_path, **{
458
+ k: v for k, v in kwargs.items()
459
+ if k in ("trust_remote_code", "revision", "cache_dir")
460
+ }
461
+ )
462
+
463
+ base = Lfm2Model.from_pretrained(
464
+ pretrained_model_name_or_path, *model_args, config=config, **kwargs
465
+ )
466
+
467
+ instance = cls.__new__(cls)
468
+ Lfm2Model.__init__(instance, config)
469
+ instance.load_state_dict(base.state_dict(), strict=True)
470
+ del base
471
+
472
+ instance._make_bidirectional()
473
+ return instance
474
+
475
+ def forward(
476
+ self,
477
+ input_ids: torch.LongTensor = None,
478
+ attention_mask: torch.Tensor = None,
479
+ position_ids: torch.LongTensor = None,
480
+ inputs_embeds: torch.Tensor = None,
481
+ output_hidden_states: bool = False,
482
+ return_dict: bool = True,
483
+ **kwargs,
484
+ ) -> BaseModelOutput:
485
+ kwargs.pop("past_key_values", None)
486
+ kwargs.pop("use_cache", None)
487
+ kwargs.pop("cache_position", None)
488
+
489
+ if inputs_embeds is None:
490
+ inputs_embeds = self.embed_tokens(input_ids)
491
+
492
+ batch_size, seq_len, _ = inputs_embeds.shape
493
+ device = inputs_embeds.device
494
+
495
+ cache_position = torch.arange(seq_len, device=device)
496
+ if position_ids is None:
497
+ position_ids = cache_position.unsqueeze(0).expand(batch_size, -1)
498
+
499
+ if attention_mask is not None and attention_mask.dim() == 2:
500
+ key_mask = attention_mask[:, None, None, :].expand(batch_size, 1, seq_len, seq_len)
501
+ query_mask = attention_mask[:, :, None, None].expand(batch_size, seq_len, 1, seq_len)
502
+ combined = (key_mask * query_mask.transpose(1, 2)).to(inputs_embeds.dtype)
503
+ bi_attn_mask = (1.0 - combined) * torch.finfo(inputs_embeds.dtype).min
504
+ linear_mask = attention_mask
505
+ else:
506
+ bi_attn_mask = attention_mask
507
+ linear_mask = None
508
+
509
+ hidden_states = inputs_embeds
510
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
511
+ all_hidden_states = (hidden_states,) if output_hidden_states else None
512
+
513
+ for layer in self.layers[:self.config.num_hidden_layers]:
514
+ layer_mask = bi_attn_mask if layer.is_attention_layer else linear_mask
515
+ hidden_states = layer(
516
+ hidden_states,
517
+ attention_mask=layer_mask,
518
+ position_embeddings=position_embeddings,
519
+ position_ids=position_ids,
520
+ past_key_values=None,
521
+ cache_position=cache_position,
522
+ )
523
+ if output_hidden_states:
524
+ all_hidden_states = all_hidden_states + (hidden_states,)
525
+
526
+ hidden_states = self.embedding_norm(hidden_states)
527
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
528
+
529
+
530
+ class Lfm2BiForCausalLM(Lfm2ForCausalLM):
531
+ @classmethod
532
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
533
+ model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
534
+ model.model.__class__ = Lfm2BiModel
535
+ model.model._make_bidirectional()
536
+ return model
537
+
538
+
539
+ # ===========================================================================
540
+ # 4. ENVIRONMENT MODULE PATH SPOOFING & FACTORY INJECTION
541
+ # ===========================================================================
542
+
543
+ Lfm2BiModel.__module__ = Lfm2Model.__module__
544
+ Lfm2BiForCausalLM.__module__ = Lfm2ForCausalLM.__module__
545
+
546
+ config = AutoConfig.from_pretrained("LiquidAI/LFM2.5-350M", trust_remote_code=True)
547
+ config_class = type(config)
548
+
549
+ AutoModel.register(config_class, Lfm2BiModel, exist_ok=True)
550
+ AutoModelForCausalLM.register(config_class, Lfm2BiForCausalLM, exist_ok=True)
551
+ print("[Launcher] Architectures forced into Hugging Face registry map successfully.")
552
+
553
+
554
+ # ===========================================================================
555
+ # 5. RUNTIME SYSTEM ARGUMENT HIJACK & EXECUTION
556
+ # ===========================================================================
557
+ if __name__ == "__main__":
558
+ config_file_name = "mntp_config.json"
559
+ sys.argv = [sys.argv[0], config_file_name]
560
+
561
+ print(f"[Launcher] Relaying pipeline configurations over to LLM2Vec engine using: {config_file_name}")
562
+ run_mntp.main()
563
+ """
564
+
565
+ with open("run_lfm2_mntp.py", "w") as f:
566
+ f.write(script_content)
567
+
568
+ print("Successfully patched run_lfm2_mntp.py for backward-compatibility wrapper support.")
569
+
570
+
571
+ get_ipython().getoutput("python run_lfm2_mntp.py")
572
+
573
+
574
+ import os
575
+
576
+ file_path = "/kaggle/working/llm2vec/experiments/run_mntp.py"
577
+
578
+ if os.path.exists(file_path):
579
+ with open(file_path, "r") as f:
580
+ content = f.read()
581
+
582
+ # 1. Strip the telemetry import statement entirely
583
+ content = content.replace(
584
+ "from transformers.utils import send_example_telemetry",
585
+ "# Telemetry stripped for modern transformers compatibility"
586
+ )
587
+
588
+ # 2. Clean up any remnants of the old TPU utility if still present
589
+ content = content.replace("is_torch_tpu_available,", "")
590
+ content = content.replace("is_torch_tpu_available", "")
591
+
592
+ # 3. Inject safe local dummy stubs right at the top of the file
593
+ fallback_stubs = (
594
+ "\n# Compatibility fallbacks for deprecated HF utilities\n"
595
+ "is_torch_tpu_available = lambda *args, **kwargs: False\n"
596
+ "send_example_telemetry = lambda *args, **kwargs: None\n\n"
597
+ )
598
+ patched_content = fallback_stubs + content
599
+
600
+ with open(file_path, "w") as f:
601
+ f.write(patched_content)
602
+
603
+ print("[Success] Cleaned up telemetry and TPU dependencies in run_mntp.py.")
604
+ else:
605
+ print(f"[Error] Could not find script at {file_path}.")
606
+
607
+
608
+ import urllib.request
609
+ import os
610
+
611
+ file_path = "/kaggle/working/llm2vec/experiments/run_mntp.py"
612
+
613
+ print("[1/3] Restoring a clean, pristine copy of run_mntp.py...")
614
+ try:
615
+ # Try fetching a fresh copy directly from the repository source
616
+ url = "https://raw.githubusercontent.com/McGill-NLP/llm2vec/main/experiments/run_mntp.py"
617
+ urllib.request.urlretrieve(url, file_path)
618
+ print(" -> Successfully restored original file via source download.")
619
+ except Exception:
620
+ # Fallback to local git repository rollback if offline
621
+ os.system(f"git checkout -- {file_path}")
622
+ print(" -> Successfully restored original file via git checkout.")
623
+
624
+ print("[2/3] Applying precise line-by-line patches...")
625
+ with open(file_path, "r") as f:
626
+ lines = f.readlines()
627
+
628
+ patched_lines = []
629
+ for line in lines:
630
+ # Safely strip out the deprecated TPU check item from imports
631
+ if "is_torch_tpu_available" in line:
632
+ line = line.replace("is_torch_tpu_available,", "").replace("is_torch_tpu_available", "")
633
+
634
+ # Safely neutralize the telemetry logging import line
635
+ if "send_example_telemetry" in line:
636
+ line = " # Telemetry logging removed for modern transformers compatibility\n"
637
+
638
+ patched_lines.append(line)
639
+
640
+ # Prepend explicit safe dummy definitions right at the absolute top of the file
641
+ fallback_headers = [
642
+ "is_torch_tpu_available = lambda *args, **kwargs: False\n",
643
+ "send_example_telemetry = lambda *args, **kwargs: None\n\n"
644
+ ]
645
+
646
+ with open(file_path, "w") as f:
647
+ f.writelines(fallback_headers + patched_lines)
648
+
649
+ print("[3/3] Done! The file is clean, uncorrupted, and syntactically sound.")
650
+
651
+
652
+ # Clone the repository locally to access the experiment files
653
+ get_ipython().getoutput("git clone https://github.com/McGill-NLP/llm2vec.git")
654
+ get_ipython().getoutput("pip install -e ./llm2vec")
655
+ get_ipython().getoutput("pip install flash-attn --no-build-isolation")
656
+
657
+
658
+
659
+
660
+
661
+ # ── Cell 1: Numbers ───────────────────────────────────────────────────────
662
+
663
+ # Training config (must match mntp_config.json)
664
+ STEPS = 2000
665
+ BATCH_PER_DEVICE = 16
666
+ GRAD_ACCUM = 4
667
+ SEQ_LEN = 512
668
+ BUFFER_FACTOR = 10 # 10x safety buffer over minimum
669
+
670
+ # Split
671
+ TRAIN_RATIO = 0.98
672
+ VAL_RATIO = 0.02
673
+
674
+ # Sampling
675
+ DOCS_PER_DOMAIN = 100_000 # equal for every domain in AraMix
676
+ NUM_DOMAINS = 26 # will verify after scan
677
+ ARAMIX_TOTAL = DOCS_PER_DOMAIN * NUM_DOMAINS # 2,600,000
678
+
679
+ # Wikipedia: solve wiki / (wiki + aramix) = 0.20
680
+ WIKI_TOTAL = int(ARAMIX_TOTAL * 0.20 / 0.80) # 650,000
681
+
682
+ GRAND_TOTAL = ARAMIX_TOTAL + WIKI_TOTAL # 3,250,000
683
+ TRAIN_SIZE = int(GRAND_TOTAL * TRAIN_RATIO) # 3,185,000
684
+ VAL_SIZE = GRAND_TOTAL - TRAIN_SIZE # 65,000
685
+
686
+ # Misc
687
+ ARAMIX_CONFIG = 'minhash_deduped' # or 'sentence_deduped'
688
+ MIN_WORDS = 30 # skip very short documents
689
+ SEED = 42
690
+
691
+ print('=' * 50)
692
+ print(f'AraMix docs (80%) : {ARAMIX_TOTAL:>10,} ({DOCS_PER_DOMAIN:,} Γ— {NUM_DOMAINS} domains)')
693
+ print(f'Wikipedia docs(20%) : {WIKI_TOTAL:>10,}')
694
+ print(f'Grand total : {GRAND_TOTAL:>10,}')
695
+ print(f'Train (98%) : {TRAIN_SIZE:>10,}')
696
+ print(f'Val ( 2%) : {VAL_SIZE:>10,}')
697
+ print('=' * 50)
698
+
699
+
700
+ # ── Cell 2: Install & imports ─────────────────────────────────────────────
701
+
702
+ # !pip uninstall -y pyarrow datasets
703
+ # !pip install --no-cache datasets
704
+ import os
705
+ import json
706
+ import random
707
+ from pathlib import Path
708
+ from collections import defaultdict, Counter
709
+
710
+ import pandas as pd
711
+ # import pyarrow as pa
712
+ # import pyarrow.parquet as pq
713
+ from datasets import load_dataset
714
+
715
+ SAVE_DIR = Path('/kaggle/working')
716
+ random.seed(SEED)
717
+
718
+ print('Ready.')
719
+
720
+
721
+ # ── Cell 3: Discover all AraMix domains (quick scan) ─────────────────────
722
+ # Scan first 500K docs to find every unique domain name.
723
+ # Takes ~5 min. Avoids hardcoding domain names.
724
+
725
+ SCAN_LIMIT = 500_000
726
+ print(f'Scanning {SCAN_LIMIT:,} docs to discover domains...')
727
+
728
+ ds_scan = load_dataset(
729
+ 'AdaMLLab/AraMix-domain-classified',
730
+ ARAMIX_CONFIG,
731
+ split='train',
732
+ streaming=True,
733
+ trust_remote_code=True,
734
+ )
735
+
736
+ domain_counter = Counter()
737
+ for i, doc in enumerate(ds_scan):
738
+ domain_counter[doc.get('domain', 'unknown')] += 1
739
+ if i + 1 >= SCAN_LIMIT:
740
+ break
741
+
742
+ ALL_DOMAINS = sorted(domain_counter.keys())
743
+ NUM_DOMAINS = len(ALL_DOMAINS)
744
+
745
+ # Recalculate totals if domain count differs from estimate
746
+ ARAMIX_TOTAL = DOCS_PER_DOMAIN * NUM_DOMAINS
747
+ WIKI_TOTAL = int(ARAMIX_TOTAL * 0.20 / 0.80)
748
+ GRAND_TOTAL = ARAMIX_TOTAL + WIKI_TOTAL
749
+ TRAIN_SIZE = int(GRAND_TOTAL * TRAIN_RATIO)
750
+ VAL_SIZE = GRAND_TOTAL - TRAIN_SIZE
751
+
752
+ print(f'\nFound {NUM_DOMAINS} domains:\n')
753
+ print(f'{"Domain":<40} {"In scan":>8} {"% of scan":>9}')
754
+ print('-' * 62)
755
+ for domain, count in domain_counter.most_common():
756
+ print(f'{domain:<40} {count:>8,} {count/SCAN_LIMIT*100:>8.1f}%')
757
+
758
+ print(f'\nUpdated totals:')
759
+ print(f' AraMix : {ARAMIX_TOTAL:,}')
760
+ print(f' Wikipedia: {WIKI_TOTAL:,}')
761
+ print(f' Train : {TRAIN_SIZE:,}')
762
+ print(f' Val : {VAL_SIZE:,}')
763
+
764
+
765
+ # ── Cell 4: Stream & sample AraMix equally by domain ─────────────────────
766
+ # Each domain gets exactly DOCS_PER_DOMAIN documents.
767
+ # Streaming + shuffle buffer gives a random sample β€” not just the first N.
768
+
769
+ bucket_counts = Counter({d: 0 for d in ALL_DOMAINS})
770
+ aramix_rows = []
771
+
772
+ skipped_short = 0
773
+ skipped_full = 0
774
+ collected = 0
775
+
776
+ print(f'Sampling {DOCS_PER_DOMAIN:,} docs Γ— {NUM_DOMAINS} domains = {ARAMIX_TOTAL:,} total...')
777
+
778
+ ds = load_dataset(
779
+ 'AdaMLLab/AraMix-domain-classified',
780
+ ARAMIX_CONFIG,
781
+ split='train',
782
+ streaming=True,
783
+ trust_remote_code=True,
784
+ ).shuffle(seed=SEED, buffer_size=100_000)
785
+
786
+ for doc in ds:
787
+ domain = doc.get('domain', 'unknown')
788
+ text = doc.get('text', '')
789
+
790
+ # Unknown domain β€” skip
791
+ if domain not in bucket_counts:
792
+ continue
793
+
794
+ # Bucket full β€” skip
795
+ if bucket_counts[domain] >= DOCS_PER_DOMAIN:
796
+ skipped_full += 1
797
+ if collected >= ARAMIX_TOTAL:
798
+ break
799
+ continue
800
+
801
+ # Too short β€” skip
802
+ if len(text.split()) < MIN_WORDS:
803
+ skipped_short += 1
804
+ continue
805
+
806
+ aramix_rows.append({
807
+ 'text': text,
808
+ 'domain': domain,
809
+ 'source': doc.get('source', 'unknown'),
810
+ })
811
+ bucket_counts[domain] += 1
812
+ collected += 1
813
+
814
+ if collected % 250_000 == 0:
815
+ filled = sum(1 for d in ALL_DOMAINS if bucket_counts[d] >= DOCS_PER_DOMAIN)
816
+ pct = collected / ARAMIX_TOTAL * 100
817
+ print(f' [{pct:5.1f}%] {collected:>8,} collected | {filled}/{NUM_DOMAINS} domains full | {skipped_short:,} short skipped')
818
+
819
+ if collected >= ARAMIX_TOTAL:
820
+ break
821
+
822
+ print(f'\nAraMix done: {collected:,} documents collected.')
823
+ print(f'Skipped (too short) : {skipped_short:,}')
824
+ print(f'Skipped (bucket full): {skipped_full:,}')
825
+
826
+
827
+ # ── Cell 5: Verify AraMix bucket counts ───────────────────────────────────
828
+
829
+ print(f'{"Domain":<40} {"Collected":>10} {"Status":>8}')
830
+ print('-' * 62)
831
+
832
+ incomplete = []
833
+ for domain in ALL_DOMAINS:
834
+ count = bucket_counts[domain]
835
+ status = 'βœ“' if count >= DOCS_PER_DOMAIN else f'⚠ {count:,}'
836
+ print(f'{domain:<40} {count:>10,} {status:>8}')
837
+ if count < DOCS_PER_DOMAIN:
838
+ incomplete.append((domain, count))
839
+
840
+ print()
841
+ if incomplete:
842
+ print(f'⚠ {len(incomplete)} domain(s) below target (rare domains β€” expected):')
843
+ for d, c in incomplete:
844
+ print(f' {d}: {c:,} / {DOCS_PER_DOMAIN:,}')
845
+ else:
846
+ print(f'βœ“ All {NUM_DOMAINS} domains have exactly {DOCS_PER_DOMAIN:,} documents.')
847
+
848
+
849
+ # ── Cell 6: Sample Arabic Wikipedia (650K articles) ───────────────────────
850
+ # Wikipedia Arabic 20231101.ar has ~1.2M articles.
851
+ # We sample WIKI_TOTAL (~650K = 53% of it).
852
+ # Wikipedia is entity-dense and relation-rich β€” perfect RE signal for MNTP.
853
+
854
+ print(f'Loading Arabic Wikipedia (wikimedia/wikipedia, 20231101.ar)...')
855
+ print(f'Target: {WIKI_TOTAL:,} articles')
856
+
857
+ wiki_ds = load_dataset(
858
+ 'wikimedia/wikipedia',
859
+ '20231101.ar',
860
+ split='train',
861
+ streaming=True,
862
+ trust_remote_code=True,
863
+ ).shuffle(seed=SEED, buffer_size=50_000)
864
+
865
+ wiki_rows = []
866
+ wiki_skipped = 0
867
+
868
+ for doc in wiki_ds:
869
+ text = doc.get('text', '').strip()
870
+
871
+ # Wikipedia articles can have very short stubs β€” skip them
872
+ if len(text.split()) < MIN_WORDS:
873
+ wiki_skipped += 1
874
+ continue
875
+
876
+ wiki_rows.append({
877
+ 'text': text,
878
+ 'domain': 'Wikipedia',
879
+ 'source': 'wikimedia/wikipedia',
880
+ })
881
+
882
+ if len(wiki_rows) % 100_000 == 0:
883
+ pct = len(wiki_rows) / WIKI_TOTAL * 100
884
+ print(f' [{pct:5.1f}%] {len(wiki_rows):>8,} collected | {wiki_skipped:,} stubs skipped')
885
+
886
+ if len(wiki_rows) >= WIKI_TOTAL:
887
+ break
888
+
889
+ print(f'\nWikipedia done: {len(wiki_rows):,} articles collected.')
890
+ print(f'Skipped (stubs < {MIN_WORDS} words): {wiki_skipped:,}')
891
+
892
+
893
+ # ── Cell 7: Combine β†’ shuffle β†’ train/val split ───────────────────────────
894
+
895
+ print('Combining AraMix + Wikipedia...')
896
+ all_rows = aramix_rows + wiki_rows
897
+ print(f' AraMix : {len(aramix_rows):,}')
898
+ print(f' Wikipedia : {len(wiki_rows):,}')
899
+ print(f' Total : {len(all_rows):,}')
900
+
901
+ # Shuffle before splitting so train/val are not domain-sorted
902
+ print('\nShuffling...')
903
+ random.shuffle(all_rows)
904
+
905
+ # Split
906
+ actual_train_size = int(len(all_rows) * TRAIN_RATIO)
907
+ train_rows = all_rows[:actual_train_size]
908
+ val_rows = all_rows[actual_train_size:]
909
+
910
+ print(f'\nSplit:')
911
+ print(f' Train : {len(train_rows):,} ({len(train_rows)/len(all_rows)*100:.1f}%)')
912
+ print(f' Val : {len(val_rows):,} ({len(val_rows)/len(all_rows)*100:.1f}%)')
913
+
914
+
915
+ # ── Cell 8: Save train.parquet + val.parquet ──────────────────────────────
916
+
917
+ def save_parquet(rows, path):
918
+ df = pd.DataFrame(rows)
919
+ df.to_parquet(path, index=False, engine='pyarrow', compression='snappy')
920
+ size_gb = Path(path).stat().st_size / 1e9
921
+ print(f' Saved {len(rows):,} rows β†’ {path} ({size_gb:.2f} GB)')
922
+ return df
923
+
924
+ print('Saving...')
925
+ train_path = SAVE_DIR / 'train.parquet'
926
+ val_path = SAVE_DIR / 'val.parquet'
927
+
928
+ train_df = save_parquet(train_rows, train_path)
929
+ val_df = save_parquet(val_rows, val_path)
930
+
931
+ # Save metadata alongside
932
+ meta = {
933
+ 'aramix_config': ARAMIX_CONFIG,
934
+ 'wiki_subset': '20231101.ar',
935
+ 'docs_per_domain': DOCS_PER_DOMAIN,
936
+ 'num_domains': NUM_DOMAINS,
937
+ 'aramix_total': len(aramix_rows),
938
+ 'wiki_total': len(wiki_rows),
939
+ 'grand_total': len(all_rows),
940
+ 'train_size': len(train_rows),
941
+ 'val_size': len(val_rows),
942
+ 'train_ratio': TRAIN_RATIO,
943
+ 'min_words': MIN_WORDS,
944
+ 'seed': SEED,
945
+ 'domains': ALL_DOMAINS,
946
+ }
947
+ with open(SAVE_DIR / 'meta.json', 'w', encoding='utf-8') as f:
948
+ json.dump(meta, f, ensure_ascii=False, indent=2)
949
+
950
+ print('\nDone. Files saved:')
951
+ for p in [train_path, val_path, SAVE_DIR / 'meta.json']:
952
+ print(f' {p}')
953
+
954
+
955
+ # ── Cell 9: Sanity check ──────────────────────────────────────────────────
956
+
957
+ print('=== TRAIN ===')
958
+ print(f'Rows : {len(train_df):,}')
959
+ print(f'Columns: {list(train_df.columns)}')
960
+
961
+ print('\nDomain distribution in train:')
962
+ domain_dist = train_df['domain'].value_counts()
963
+ for domain, count in domain_dist.items():
964
+ bar = 'β–ˆ' * int(count / domain_dist.max() * 30)
965
+ print(f' {domain:<35} {count:>8,} {bar}')
966
+
967
+ print('\nSource distribution in train:')
968
+ print(train_df['source'].value_counts().to_string())
969
+
970
+ train_df['word_count'] = train_df['text'].str.split().str.len()
971
+ print(f'\nWord count stats (train):')
972
+ print(f' Mean : {train_df["word_count"].mean():.0f}')
973
+ print(f' Median: {train_df["word_count"].median():.0f}')
974
+ print(f' Min : {train_df["word_count"].min()}')
975
+ print(f' Max : {train_df["word_count"].max():,}')
976
+ print(f'\nEstimated total tokens (Γ—1.3 tok/word):')
977
+ print(f' Train : {train_df["word_count"].sum() * 1.3 / 1e6:.0f}M')
978
+
979
+ val_df['word_count'] = val_df['text'].str.split().str.len()
980
+ print(f' Val : {val_df["word_count"].sum() * 1.3 / 1e6:.0f}M')
981
+
982
+ print('\n=== VAL ===')
983
+ print(f'Rows : {len(val_df):,}')
984
+ print('Domain distribution in val:')
985
+ print(val_df['domain'].value_counts().to_string())
986
+
987
+ print('\nβœ“ All done. Upload /kaggle/working/train.parquet and val.parquet to your dataset.')
988
+
989
+
990
+
__notebook__.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\"\"\"\nmodeling_lfm2_bi.py\n-------------------\nBidirectional LFM2 model for encoder tasks (MNTP, NER, RE).\n\ncomponents:\n - Lfm2BiModel: backbone with bidirectional attention + symmetric convolutions\n\nBug fixes over original submission:\n 1. CUDA fast path (causal_conv1d_fn) bypassed via forward() override\n 2. from_pretrained loads causal LM weights cleanly (no double conversion)\n 3. Proper 4D attention mask construction for GQA layers\n\"\"\"\n\nimport types\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom transformers import AutoConfig\nfrom transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput\nfrom transformers.models.lfm2.modeling_lfm2 import (\n Lfm2ForCausalLM,\n Lfm2Model,\n Lfm2PreTrainedModel,\n Lfm2ShortConv,\n)\n\n\n# ---------------------------------------------------------------------------\n# Core conversion: causal conv β†’ bidirectional conv\n# ---------------------------------------------------------------------------\n\ndef _make_conv_bidirectional(conv_module: Lfm2ShortConv) -> None:\n \"\"\"\n Convert a single Lfm2ShortConv layer to bidirectional in-place.\n\n How the original causal conv works (confirmed from source):\n self.conv = nn.Conv1d(..., padding=L_cache-1) # left-only padding\n conv_out = self.conv(Bx)[..., :seqlen] # trim excess right tokens\n\n For kernel_size=4 (LFM2-350M), original padding=3:\n output_len = T + 2*3 - 4 + 1 = T + 3 β†’ [:T] = T βœ“ (causal left-only)\n\n Bidirectional fix β€” replace with symmetric padding=kernel_size//2=2:\n output_len = T + 2*2 - 4 + 1 = T + 1 β†’ [:T] = T βœ“ (center-padded)\n\n Critical: override forward() to always call slow_forward().\n Without this, CUDA path calls causal_conv1d_fn and ignores self.conv entirely.\n \"\"\"\n kernel_size = conv_module.L_cache # == config.conv_L_cache (4 for LFM2-350M)\n old_conv = conv_module.conv\n\n # Replace conv with symmetric padding version, copy pretrained weights\n new_conv = nn.Conv1d(\n in_channels=old_conv.in_channels,\n out_channels=old_conv.out_channels,\n kernel_size=kernel_size,\n groups=old_conv.groups,\n bias=old_conv.bias is not None,\n padding=kernel_size // 2, # symmetric: equal left and right context\n )\n new_conv.weight.data.copy_(old_conv.weight.data)\n if old_conv.bias is not None:\n new_conv.bias.data.copy_(old_conv.bias.data)\n\n conv_module.conv = new_conv\n\n # Override forward to bypass causal CUDA kernel (causal_conv1d_fn).\n # slow_forward calls self.conv which is now the symmetric version.\n def _bidirectional_forward(\n self,\n hidden_states: torch.Tensor,\n past_key_values=None,\n cache_position=None,\n attention_mask=None,\n **kwargs,\n ) -> torch.Tensor:\n # Force slow_forward β€” never causal_conv1d_fn\n return self.slow_forward(\n hidden_states,\n past_key_values=None, # no caching during encoding\n cache_position=cache_position,\n attention_mask=attention_mask,\n )\n\n conv_module.forward = types.MethodType(_bidirectional_forward, conv_module)\n\n\n# ---------------------------------------------------------------------------\n# Bidirectional backbone\n# ---------------------------------------------------------------------------\n\nclass Lfm2BiModel(Lfm2Model):\n \"\"\"\n LFM2 backbone converted to bidirectional operation.\n\n Changes vs Lfm2Model:\n - GQA layers: full 4D attention mask (no causal triangular mask)\n - Conv layers: symmetric padding + slow_forward forced (via _make_conv_bidirectional)\n\n State dict keys are identical to Lfm2Model for clean weight loading.\n \"\"\"\n\n def __init__(self, config):\n super().__init__(config)\n # Do NOT call _make_bidirectional here β€” weights are random at init.\n # It is called in from_pretrained after weights are loaded.\n\n def _make_bidirectional(self) -> None:\n \"\"\"Convert all conv and attention layers in-place.\"\"\"\n converted_conv = 0\n for layer in self.layers:\n # 1. Convert convolutions\n if not layer.is_attention_layer and hasattr(layer, \"conv\"):\n _make_conv_bidirectional(layer.conv)\n converted_conv += 1\n \n # 2. Safety check: Ensure attention blocks don't force causal behavior\n elif layer.is_attention_layer and hasattr(layer, \"attn\"):\n # If your inspection shows an internal 'is_causal' attribute, kill it here:\n if hasattr(layer.attn, \"is_causal\"):\n layer.attn.is_causal = False\n\n print(f\"[Lfm2BiModel] Converted {converted_conv} conv layers. Attention maps unconstrained.\")\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n \"\"\"\n Load pretrained Lfm2Model weights then apply bidirectional conversion.\n\n Clean flow:\n 1. Load into standard Lfm2Model (causal) to get pretrained weights\n 2. Transfer weights to Lfm2BiModel instance\n 3. Apply _make_bidirectional() exactly once\n \"\"\"\n config = kwargs.pop(\"config\", None)\n if config is None:\n config = AutoConfig.from_pretrained(\n pretrained_model_name_or_path, **{\n k: v for k, v in kwargs.items()\n if k in (\"trust_remote_code\", \"revision\", \"cache_dir\")\n }\n )\n\n # Load causal model with pretrained weights\n base = Lfm2Model.from_pretrained(\n pretrained_model_name_or_path, *model_args, config=config, **kwargs\n )\n\n # Build bidirectional instance and transfer weights\n # Use __new__ + parent __init__ to avoid calling _make_bidirectional prematurely\n instance = cls.__new__(cls)\n Lfm2Model.__init__(instance, config)\n instance.load_state_dict(base.state_dict(), strict=True)\n\n del base # free causal model memory\n\n # Apply bidirectional conversion once with pretrained weights in place\n instance._make_bidirectional()\n\n return instance\n\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: torch.Tensor = None,\n position_ids: torch.LongTensor = None,\n inputs_embeds: torch.Tensor = None,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n **kwargs,\n ) -> BaseModelOutput:\n # Drop generation-only kwargs\n kwargs.pop(\"past_key_values\", None)\n kwargs.pop(\"use_cache\", None)\n kwargs.pop(\"cache_position\", None)\n\n if inputs_embeds is None:\n inputs_embeds = self.embed_tokens(input_ids)\n\n batch_size, seq_len, _ = inputs_embeds.shape\n device = inputs_embeds.device\n\n # Position ids: full sequence, no offset\n cache_position = torch.arange(seq_len, device=device)\n if position_ids is None:\n position_ids = cache_position.unsqueeze(0).expand(batch_size, -1)\n\n # --- Attention mask for GQA layers (4D additive) ---\n # Shape: (B, 1, T, T) β€” 0 = attend, -inf = ignore\n if attention_mask is not None and attention_mask.dim() == 2:\n # (B, T) binary mask β†’ (B, 1, T, T) additive mask\n # Key mask: which keys to ignore\n key_mask = attention_mask[:, None, None, :].expand(\n batch_size, 1, seq_len, seq_len\n ) # 1 = keep, 0 = pad\n # Query mask: ignore rows where query is padding\n query_mask = attention_mask[:, :, None, None].expand(\n batch_size, seq_len, 1, seq_len # will broadcast\n )\n # Combined: only attend where both query and key are real tokens\n combined = (key_mask * query_mask.transpose(1, 2)).to(inputs_embeds.dtype)\n # Convert to additive: 0 β†’ 0.0 (attend), 1 β†’ min_val (ignore)... wait\n # 1 means real token (attend), 0 means pad (ignore)\n # Additive: real=0.0, pad=very_negative\n bi_attn_mask = (1.0 - combined) * torch.finfo(inputs_embeds.dtype).min\n\n # Linear mask for conv layers: 2D binary (B, T)\n linear_mask = attention_mask\n elif attention_mask is not None:\n # Already in 4D or other format, use as-is\n bi_attn_mask = attention_mask\n linear_mask = None\n else:\n bi_attn_mask = None\n linear_mask = None\n\n # --- Forward through layers ---\n hidden_states = inputs_embeds\n position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)\n\n all_hidden_states = (hidden_states,) if output_hidden_states else None\n\n for layer in self.layers[:self.config.num_hidden_layers]:\n # GQA layers get 4D mask, conv layers get 2D binary mask\n layer_mask = bi_attn_mask if layer.is_attention_layer else linear_mask\n\n hidden_states = layer(\n hidden_states,\n attention_mask=layer_mask,\n position_embeddings=position_embeddings,\n position_ids=position_ids,\n past_key_values=None,\n cache_position=cache_position,\n )\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n hidden_states = self.embedding_norm(hidden_states)\n\n return BaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n )\n\n\n\nclass Lfm2BiForCausalLM(Lfm2ForCausalLM):\n \"\"\"\n Causal LM wrapper that patches the underlying Lfm2Model backbone \n with your bidirectional Lfm2BiModel for MNTP training.\n \"\"\"\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n # 1. Load the original causal model (brings in backbone + lm_head weights)\n model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n \n # 2. Dynamically change the backbone class to your bidirectional version\n model.model.__class__ = Lfm2BiModel\n \n # 3. Execute your in-place conv transformations \n model.model._make_bidirectional()\n \n return model\n\n\n\n\n# Spoof the module paths so Hugging Face can find a physical __file__\nLfm2BiModel.__module__ = Lfm2Model.__module__\n\n# Do the same for your CausalLM wrapper if you're using Phase 1\nif 'Lfm2BiForCausalLM' in globals():\n Lfm2BiForCausalLM.__module__ = Lfm2ForCausalLM.__module__\nmodel = Lfm2BiModel.from_pretrained(\"LiquidAI/LFM2.5-350M\")\nfrom transformers import AutoConfig, AutoModel, AutoModelForCausalLM\n\n# Load config to grab its class mapping\nconfig = AutoConfig.from_pretrained(\"LiquidAI/LFM2.5-350M\") # or your specific model path\nconfig_class = type(config)\n\n\nAutoModel.register(config_class, Lfm2BiModel, exist_ok=True)\nAutoModelForCausalLM.register(config_class, Lfm2BiForCausalLM, exist_ok=True)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from transformers import Lfm2ForCausalLM\n\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"config = ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import json\n\nmntp_config = {\n \"model_name_or_path\": \"LiquidAI/LFM2.5-350M\",\n \"dataset_name\": \"wikitext\",\n \"dataset_config_name\": \"wikitext-103-raw-v1\",\n \"per_device_train_batch_size\": 8,\n \"per_device_eval_batch_size\": 8,\n \"gradient_accumulation_steps\": 4,\n \"do_train\": True,\n \"do_eval\": True,\n \"max_seq_length\": 512,\n \"mask_token_type\": \"blank\",\n \"data_collator_type\": \"all_mask\",\n \"mlm_probability\": 0.15,\n \"overwrite_output_dir\": True,\n \"output_dir\": \"output/LFM2.5-350M-MNTP\",\n \"evaluation_strategy\": \"steps\",\n \"eval_steps\": 100,\n \"save_steps\": 200,\n \"stop_after_n_steps\": 1000,\n \"lora_r\": 16,\n \"gradient_checkpointing\": True,\n \"torch_dtype\": \"bfloat16\",\n \"trust_remote_code\": True\n}\n\nwith open(\"mntp_config.json\", \"w\") as f:\n json.dump(mntp_config, f, indent=4)\n\nprint(\"Successfully generated mntp_config.json in workspace.\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"script_content = \"\"\"import types\nimport sys\nimport os\nimport torch\nimport torch.nn as nn\n\n# ===========================================================================\n# 0. BACKWARD COMPATIBILITY MONKEYPATCH (Fixes llm2vec TPU import error)\n# ===========================================================================\nimport transformers\nif not hasattr(transformers, \"is_torch_tpu_available\"):\n # Injects a dummy fallback function since newer transformers removed it from root.\n # Safe for GPU/CPU environments.\n transformers.is_torch_tpu_available = lambda *args, **kwargs: False\n\nfrom transformers import AutoConfig, AutoModel, AutoModelForCausalLM\nfrom transformers.modeling_outputs import BaseModelOutput\n\n# Dynamically locate the experiments directory based on your workspace layout\nif os.path.exists(\"./experiments\"):\n sys.path.append(os.path.abspath(\"./experiments\"))\nelif os.path.exists(\"./llm2vec/experiments\"):\n sys.path.append(os.path.abspath(\"./llm2vec/experiments\"))\nelse:\n raise FileNotFoundError(\"Could not find the llm2vec 'experiments' directory in your workspace.\")\n\nimport run_mntp \n\n# ===========================================================================\n# 1. DYNAMIC CLASS EXTRACTION \n# ===========================================================================\nprint(\"[Launcher] Fetching base model blueprint to dynamically extract remote code architectures...\")\ntry:\n base_dummy = AutoModelForCausalLM.from_pretrained(\n \"LiquidAI/LFM2.5-350M\", \n trust_remote_code=True,\n torch_dtype=torch.bfloat16\n )\n Lfm2ForCausalLM = base_dummy.__class__\n Lfm2Model = base_dummy.model.__class__\n \n Lfm2ShortConv = None\n for layer in base_dummy.model.layers:\n if hasattr(layer, \"conv\"):\n Lfm2ShortConv = layer.conv.__class__\n break\n \n if Lfm2ShortConv is None:\n raise AttributeError(\"Could not dynamically trace Lfm2ShortConv from architecture layers.\")\n \n print(f\"[Launcher] Safely extracted classes: {Lfm2ForCausalLM.__name__}, {Lfm2Model.__name__}\")\n \n del base_dummy\n torch.cuda.empty_cache()\nexcept Exception as e:\n print(f\"[Launcher] Fallback failed during runtime reflection setup: {e}\")\n raise e\n\n# ===========================================================================\n# 2. CORE BIDIRECTIONAL CONVERSION ENGINE\n# ===========================================================================\n\ndef _make_conv_bidirectional(conv_module: Lfm2ShortConv) -> None:\n kernel_size = conv_module.L_cache \n old_conv = conv_module.conv\n\n new_conv = nn.Conv1d(\n in_channels=old_conv.in_channels,\n out_channels=old_conv.out_channels,\n kernel_size=kernel_size,\n groups=old_conv.groups,\n bias=old_conv.bias is not None,\n padding=kernel_size // 2, \n )\n new_conv.weight.data.copy_(old_conv.weight.data)\n if old_conv.bias is not None:\n new_conv.bias.data.copy_(old_conv.bias.data)\n\n conv_module.conv = new_conv\n\n def _bidirectional_forward(\n self,\n hidden_states: torch.Tensor,\n past_key_values=None,\n cache_position=None,\n attention_mask=None,\n **kwargs,\n ) -> torch.Tensor:\n return self.slow_forward(\n hidden_states,\n past_key_values=None, \n cache_position=cache_position,\n attention_mask=attention_mask,\n )\n\n conv_module.forward = types.MethodType(_bidirectional_forward, conv_module)\n\n\n# ===========================================================================\n# 3. BIDIRECTIONAL MODEL BACKBONE DEFINITIONS\n# ===========================================================================\n\nclass Lfm2BiModel(Lfm2Model):\n def __init__(self, config):\n super().__init__(config)\n\n def _make_bidirectional(self) -> None:\n converted_conv = 0\n for layer in self.layers:\n if not layer.is_attention_layer and hasattr(layer, \"conv\"):\n _make_conv_bidirectional(layer.conv)\n converted_conv += 1\n elif layer.is_attention_layer and hasattr(layer, \"attn\"):\n if hasattr(layer.attn, \"is_causal\"):\n layer.attn.is_causal = False\n print(f\"[Lfm2BiModel] Applied modifications across {converted_conv} conv layers.\")\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n config = kwargs.pop(\"config\", None)\n if config is None:\n config = AutoConfig.from_pretrained(\n pretrained_model_name_or_path, **{\n k: v for k, v in kwargs.items()\n if k in (\"trust_remote_code\", \"revision\", \"cache_dir\")\n }\n )\n\n base = Lfm2Model.from_pretrained(\n pretrained_model_name_or_path, *model_args, config=config, **kwargs\n )\n\n instance = cls.__new__(cls)\n Lfm2Model.__init__(instance, config)\n instance.load_state_dict(base.state_dict(), strict=True)\n del base \n\n instance._make_bidirectional()\n return instance\n\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: torch.Tensor = None,\n position_ids: torch.LongTensor = None,\n inputs_embeds: torch.Tensor = None,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n **kwargs,\n ) -> BaseModelOutput:\n kwargs.pop(\"past_key_values\", None)\n kwargs.pop(\"use_cache\", None)\n kwargs.pop(\"cache_position\", None)\n\n if inputs_embeds is None:\n inputs_embeds = self.embed_tokens(input_ids)\n\n batch_size, seq_len, _ = inputs_embeds.shape\n device = inputs_embeds.device\n\n cache_position = torch.arange(seq_len, device=device)\n if position_ids is None:\n position_ids = cache_position.unsqueeze(0).expand(batch_size, -1)\n\n if attention_mask is not None and attention_mask.dim() == 2:\n key_mask = attention_mask[:, None, None, :].expand(batch_size, 1, seq_len, seq_len)\n query_mask = attention_mask[:, :, None, None].expand(batch_size, seq_len, 1, seq_len)\n combined = (key_mask * query_mask.transpose(1, 2)).to(inputs_embeds.dtype)\n bi_attn_mask = (1.0 - combined) * torch.finfo(inputs_embeds.dtype).min\n linear_mask = attention_mask\n else:\n bi_attn_mask = attention_mask\n linear_mask = None\n\n hidden_states = inputs_embeds\n position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)\n all_hidden_states = (hidden_states,) if output_hidden_states else None\n\n for layer in self.layers[:self.config.num_hidden_layers]:\n layer_mask = bi_attn_mask if layer.is_attention_layer else linear_mask\n hidden_states = layer(\n hidden_states,\n attention_mask=layer_mask,\n position_embeddings=position_embeddings,\n position_ids=position_ids,\n past_key_values=None,\n cache_position=cache_position,\n )\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n hidden_states = self.embedding_norm(hidden_states)\n return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)\n\n\nclass Lfm2BiForCausalLM(Lfm2ForCausalLM):\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n model.model.__class__ = Lfm2BiModel\n model.model._make_bidirectional()\n return model\n\n\n# ===========================================================================\n# 4. ENVIRONMENT MODULE PATH SPOOFING & FACTORY INJECTION\n# ===========================================================================\n\nLfm2BiModel.__module__ = Lfm2Model.__module__\nLfm2BiForCausalLM.__module__ = Lfm2ForCausalLM.__module__\n\nconfig = AutoConfig.from_pretrained(\"LiquidAI/LFM2.5-350M\", trust_remote_code=True)\nconfig_class = type(config)\n\nAutoModel.register(config_class, Lfm2BiModel, exist_ok=True)\nAutoModelForCausalLM.register(config_class, Lfm2BiForCausalLM, exist_ok=True)\nprint(\"[Launcher] Architectures forced into Hugging Face registry map successfully.\")\n\n\n# ===========================================================================\n# 5. RUNTIME SYSTEM ARGUMENT HIJACK & EXECUTION\n# ===========================================================================\nif __name__ == \"__main__\":\n config_file_name = \"mntp_config.json\"\n sys.argv = [sys.argv[0], config_file_name]\n \n print(f\"[Launcher] Relaying pipeline configurations over to LLM2Vec engine using: {config_file_name}\")\n run_mntp.main()\n\"\"\"\n\nwith open(\"run_lfm2_mntp.py\", \"w\") as f:\n f.write(script_content)\n\nprint(\"Successfully patched run_lfm2_mntp.py for backward-compatibility wrapper support.\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python run_lfm2_mntp.py","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nfile_path = \"/kaggle/working/llm2vec/experiments/run_mntp.py\"\n\nif os.path.exists(file_path):\n with open(file_path, \"r\") as f:\n content = f.read()\n\n # 1. Strip the telemetry import statement entirely\n content = content.replace(\n \"from transformers.utils import send_example_telemetry\", \n \"# Telemetry stripped for modern transformers compatibility\"\n )\n\n # 2. Clean up any remnants of the old TPU utility if still present\n content = content.replace(\"is_torch_tpu_available,\", \"\")\n content = content.replace(\"is_torch_tpu_available\", \"\")\n\n # 3. Inject safe local dummy stubs right at the top of the file\n fallback_stubs = (\n \"\\n# Compatibility fallbacks for deprecated HF utilities\\n\"\n \"is_torch_tpu_available = lambda *args, **kwargs: False\\n\"\n \"send_example_telemetry = lambda *args, **kwargs: None\\n\\n\"\n )\n patched_content = fallback_stubs + content\n\n with open(file_path, \"w\") as f:\n f.write(patched_content)\n\n print(\"[Success] Cleaned up telemetry and TPU dependencies in run_mntp.py.\")\nelse:\n print(f\"[Error] Could not find script at {file_path}.\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import urllib.request\nimport os\n\nfile_path = \"/kaggle/working/llm2vec/experiments/run_mntp.py\"\n\nprint(\"[1/3] Restoring a clean, pristine copy of run_mntp.py...\")\ntry:\n # Try fetching a fresh copy directly from the repository source\n url = \"https://raw.githubusercontent.com/McGill-NLP/llm2vec/main/experiments/run_mntp.py\"\n urllib.request.urlretrieve(url, file_path)\n print(\" -> Successfully restored original file via source download.\")\nexcept Exception:\n # Fallback to local git repository rollback if offline\n os.system(f\"git checkout -- {file_path}\")\n print(\" -> Successfully restored original file via git checkout.\")\n\nprint(\"[2/3] Applying precise line-by-line patches...\")\nwith open(file_path, \"r\") as f:\n lines = f.readlines()\n\npatched_lines = []\nfor line in lines:\n # Safely strip out the deprecated TPU check item from imports\n if \"is_torch_tpu_available\" in line:\n line = line.replace(\"is_torch_tpu_available,\", \"\").replace(\"is_torch_tpu_available\", \"\")\n \n # Safely neutralize the telemetry logging import line\n if \"send_example_telemetry\" in line:\n line = \" # Telemetry logging removed for modern transformers compatibility\\n\"\n \n patched_lines.append(line)\n\n# Prepend explicit safe dummy definitions right at the absolute top of the file\nfallback_headers = [\n \"is_torch_tpu_available = lambda *args, **kwargs: False\\n\",\n \"send_example_telemetry = lambda *args, **kwargs: None\\n\\n\"\n]\n\nwith open(file_path, \"w\") as f:\n f.writelines(fallback_headers + patched_lines)\n\nprint(\"[3/3] Done! The file is clean, uncorrupted, and syntactically sound.\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Clone the repository locally to access the experiment files\n!git clone https://github.com/McGill-NLP/llm2vec.git\n!pip install -e ./llm2vec\n!pip install flash-attn --no-build-isolation","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ── Cell 1: Numbers ───────────────────────────────────────────────────────\n\n# Training config (must match mntp_config.json)\nSTEPS = 2000\nBATCH_PER_DEVICE = 16\nGRAD_ACCUM = 4\nSEQ_LEN = 512\nBUFFER_FACTOR = 10 # 10x safety buffer over minimum\n\n# Split\nTRAIN_RATIO = 0.98\nVAL_RATIO = 0.02\n\n# Sampling\nDOCS_PER_DOMAIN = 100_000 # equal for every domain in AraMix\nNUM_DOMAINS = 26 # will verify after scan\nARAMIX_TOTAL = DOCS_PER_DOMAIN * NUM_DOMAINS # 2,600,000\n\n# Wikipedia: solve wiki / (wiki + aramix) = 0.20\nWIKI_TOTAL = int(ARAMIX_TOTAL * 0.20 / 0.80) # 650,000\n\nGRAND_TOTAL = ARAMIX_TOTAL + WIKI_TOTAL # 3,250,000\nTRAIN_SIZE = int(GRAND_TOTAL * TRAIN_RATIO) # 3,185,000\nVAL_SIZE = GRAND_TOTAL - TRAIN_SIZE # 65,000\n\n# Misc\nARAMIX_CONFIG = 'minhash_deduped' # or 'sentence_deduped'\nMIN_WORDS = 30 # skip very short documents\nSEED = 42\n\nprint('=' * 50)\nprint(f'AraMix docs (80%) : {ARAMIX_TOTAL:>10,} ({DOCS_PER_DOMAIN:,} Γ— {NUM_DOMAINS} domains)')\nprint(f'Wikipedia docs(20%) : {WIKI_TOTAL:>10,}')\nprint(f'Grand total : {GRAND_TOTAL:>10,}')\nprint(f'Train (98%) : {TRAIN_SIZE:>10,}')\nprint(f'Val ( 2%) : {VAL_SIZE:>10,}')\nprint('=' * 50)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-15T23:12:23.476945Z","iopub.execute_input":"2026-06-15T23:12:23.477327Z","iopub.status.idle":"2026-06-15T23:12:23.483177Z","shell.execute_reply.started":"2026-06-15T23:12:23.477310Z","shell.execute_reply":"2026-06-15T23:12:23.482241Z"}},"outputs":[{"name":"stdout","text":"==================================================\nAraMix docs (80%) : 2,600,000 (100,000 Γ— 26 domains)\nWikipedia docs(20%) : 650,000\nGrand total : 3,250,000\nTrain (98%) : 3,185,000\nVal ( 2%) : 65,000\n==================================================\n","output_type":"stream"}],"execution_count":2},{"cell_type":"code","source":"# ── Cell 2: Install & imports ─────────────────────────────────────────────\n\n# !pip uninstall -y pyarrow datasets\n# !pip install --no-cache datasets\nimport os\nimport json\nimport random\nfrom pathlib import Path\nfrom collections import defaultdict, Counter\n\nimport pandas as pd\n# import pyarrow as pa\n# import pyarrow.parquet as pq\nfrom datasets import load_dataset\n\nSAVE_DIR = Path('/kaggle/working')\nrandom.seed(SEED)\n\nprint('Ready.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-15T23:12:25.150192Z","iopub.execute_input":"2026-06-15T23:12:25.150430Z","iopub.status.idle":"2026-06-15T23:12:25.154693Z","shell.execute_reply.started":"2026-06-15T23:12:25.150413Z","shell.execute_reply":"2026-06-15T23:12:25.153822Z"}},"outputs":[{"name":"stdout","text":"Ready.\n","output_type":"stream"}],"execution_count":3},{"cell_type":"code","source":"# ── Cell 3: Discover all AraMix domains (quick scan) ─────────────────────\n# Scan first 500K docs to find every unique domain name.\n# Takes ~5 min. Avoids hardcoding domain names.\n\nSCAN_LIMIT = 500_000\nprint(f'Scanning {SCAN_LIMIT:,} docs to discover domains...')\n\nds_scan = load_dataset(\n 'AdaMLLab/AraMix-domain-classified',\n ARAMIX_CONFIG,\n split='train',\n streaming=True,\n trust_remote_code=True,\n)\n\ndomain_counter = Counter()\nfor i, doc in enumerate(ds_scan):\n domain_counter[doc.get('domain', 'unknown')] += 1\n if i + 1 >= SCAN_LIMIT:\n break\n\nALL_DOMAINS = sorted(domain_counter.keys())\nNUM_DOMAINS = len(ALL_DOMAINS)\n\n# Recalculate totals if domain count differs from estimate\nARAMIX_TOTAL = DOCS_PER_DOMAIN * NUM_DOMAINS\nWIKI_TOTAL = int(ARAMIX_TOTAL * 0.20 / 0.80)\nGRAND_TOTAL = ARAMIX_TOTAL + WIKI_TOTAL\nTRAIN_SIZE = int(GRAND_TOTAL * TRAIN_RATIO)\nVAL_SIZE = GRAND_TOTAL - TRAIN_SIZE\n\nprint(f'\\nFound {NUM_DOMAINS} domains:\\n')\nprint(f'{\"Domain\":<40} {\"In scan\":>8} {\"% of scan\":>9}')\nprint('-' * 62)\nfor domain, count in domain_counter.most_common():\n print(f'{domain:<40} {count:>8,} {count/SCAN_LIMIT*100:>8.1f}%')\n\nprint(f'\\nUpdated totals:')\nprint(f' AraMix : {ARAMIX_TOTAL:,}')\nprint(f' Wikipedia: {WIKI_TOTAL:,}')\nprint(f' Train : {TRAIN_SIZE:,}')\nprint(f' Val : {VAL_SIZE:,}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-15T23:12:28.059408Z","iopub.execute_input":"2026-06-15T23:12:28.059668Z","iopub.status.idle":"2026-06-15T23:14:11.575042Z","shell.execute_reply.started":"2026-06-15T23:12:28.059647Z","shell.execute_reply":"2026-06-15T23:14:11.573944Z"}},"outputs":[{"name":"stderr","text":"`trust_remote_code` is not supported anymore.\nPlease check that the Hugging Face dataset 'AdaMLLab/AraMix-domain-classified' isn't based on a loading script and remove `trust_remote_code`.\nIf the dataset is based on a loading script, please ask the dataset author to remove it and convert it to a standard format like Parquet.\n","output_type":"stream"},{"name":"stdout","text":"Scanning 500,000 docs to discover domains...\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"README.md: 0%| | 0.00/3.09k [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"19a51db3e76f4e4397dc628cab592712"}},"metadata":{}},{"name":"stderr","text":"Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"Resolving data files: 0%| | 0/1683 [00:00<?, ?it/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"435f3d286b1f4fd386e8e654f9c5c6d4"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"Resolving data files: 0%| | 0/1683 [00:00<?, ?it/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"a0369e1fbb2249699c962a56b1ef08df"}},"metadata":{}},{"name":"stdout","text":"\nFound 26 domains:\n\nDomain In scan % of scan\n--------------------------------------------------------------\nNews 69,204 13.8%\nSensitive_Subjects 61,761 12.4%\nBusiness_and_Industrial 49,011 9.8%\nPeople_and_Society 48,491 9.7%\nSports 37,880 7.6%\nHealth 29,972 6.0%\nJobs_and_Education 23,279 4.7%\nArts_and_Entertainment 22,013 4.4%\nLaw_and_Government 20,597 4.1%\nFood_and_Drink 16,142 3.2%\nHome_and_Garden 14,249 2.8%\nFinance 13,643 2.7%\nBeauty_and_Fitness 13,127 2.6%\nTravel_and_Transportation 10,661 2.1%\nComputers_and_Electronics 10,549 2.1%\nBooks_and_Literature 10,405 2.1%\nInternet_and_Telecom 9,967 2.0%\nAutos_and_Vehicles 7,052 1.4%\nScience 5,498 1.1%\nGames 5,068 1.0%\nAdult 4,971 1.0%\nShopping 4,521 0.9%\nReal_Estate 3,917 0.8%\nHobbies_and_Leisure 3,606 0.7%\nPets_and_Animals 3,106 0.6%\nOnline_Communities 1,310 0.3%\n\nUpdated totals:\n AraMix : 2,600,000\n Wikipedia: 650,000\n Train : 3,185,000\n Val : 65,000\n","output_type":"stream"}],"execution_count":4},{"cell_type":"code","source":"# ── Cell 4: Stream & sample AraMix equally by domain ─────────────────────\n# Each domain gets exactly DOCS_PER_DOMAIN documents.\n# Streaming + shuffle buffer gives a random sample β€” not just the first N.\n\nbucket_counts = Counter({d: 0 for d in ALL_DOMAINS})\naramix_rows = []\n\nskipped_short = 0\nskipped_full = 0\ncollected = 0\n\nprint(f'Sampling {DOCS_PER_DOMAIN:,} docs Γ— {NUM_DOMAINS} domains = {ARAMIX_TOTAL:,} total...')\n\nds = load_dataset(\n 'AdaMLLab/AraMix-domain-classified',\n ARAMIX_CONFIG,\n split='train',\n streaming=True,\n trust_remote_code=True,\n).shuffle(seed=SEED, buffer_size=100_000)\n\nfor doc in ds:\n domain = doc.get('domain', 'unknown')\n text = doc.get('text', '')\n\n # Unknown domain β€” skip\n if domain not in bucket_counts:\n continue\n\n # Bucket full β€” skip\n if bucket_counts[domain] >= DOCS_PER_DOMAIN:\n skipped_full += 1\n if collected >= ARAMIX_TOTAL:\n break\n continue\n\n # Too short β€” skip\n if len(text.split()) < MIN_WORDS:\n skipped_short += 1\n continue\n\n aramix_rows.append({\n 'text': text,\n 'domain': domain,\n 'source': doc.get('source', 'unknown'),\n })\n bucket_counts[domain] += 1\n collected += 1\n\n if collected % 250_000 == 0:\n filled = sum(1 for d in ALL_DOMAINS if bucket_counts[d] >= DOCS_PER_DOMAIN)\n pct = collected / ARAMIX_TOTAL * 100\n print(f' [{pct:5.1f}%] {collected:>8,} collected | {filled}/{NUM_DOMAINS} domains full | {skipped_short:,} short skipped')\n\n if collected >= ARAMIX_TOTAL:\n break\n\nprint(f'\\nAraMix done: {collected:,} documents collected.')\nprint(f'Skipped (too short) : {skipped_short:,}')\nprint(f'Skipped (bucket full): {skipped_full:,}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-15T23:14:11.575713Z","iopub.execute_input":"2026-06-15T23:14:11.575993Z","iopub.status.idle":"2026-06-16T00:47:46.981827Z","shell.execute_reply.started":"2026-06-15T23:14:11.575977Z","shell.execute_reply":"2026-06-16T00:47:46.975558Z"}},"outputs":[{"name":"stderr","text":"`trust_remote_code` is not supported anymore.\nPlease check that the Hugging Face dataset 'AdaMLLab/AraMix-domain-classified' isn't based on a loading script and remove `trust_remote_code`.\nIf the dataset is based on a loading script, please ask the dataset author to remove it and convert it to a standard format like Parquet.\n","output_type":"stream"},{"name":"stdout","text":"Sampling 100,000 docs Γ— 26 domains = 2,600,000 total...\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"Resolving data files: 0%| | 0/1683 [00:00<?, ?it/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"468af2e446c548939c0273afd063a978"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"Resolving data files: 0%| | 0/1683 [00:00<?, ?it/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"07596fe0bdd847abb87419687511bb32"}},"metadata":{}},{"name":"stderr","text":"Got disconnected from remote data host. Retrying in 5sec [1/20]\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00513-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":" [ 9.6%] 250,000 collected | 0/26 domains full | 854 short skipped\n [ 19.2%] 500,000 collected | 0/26 domains full | 1,730 short skipped\n [ 28.8%] 750,000 collected | 2/26 domains full | 2,583 short skipped\n","output_type":"stream"},{"name":"stderr","text":"'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00656-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":" [ 38.5%] 1,000,000 collected | 3/26 domains full | 3,897 short skipped\n [ 48.1%] 1,250,000 collected | 5/26 domains full | 6,214 short skipped\n","output_type":"stream"},{"name":"stderr","text":"'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00364-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":" [ 57.7%] 1,500,000 collected | 8/26 domains full | 9,150 short skipped\n [ 67.3%] 1,750,000 collected | 9/26 domains full | 13,300 short skipped\n","output_type":"stream"},{"name":"stderr","text":"'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01150-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":" [ 76.9%] 2,000,000 collected | 14/26 domains full | 21,604 short skipped\n","output_type":"stream"},{"name":"stderr","text":"'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00123-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01299-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01300-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01575-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00023-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00113-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":" [ 86.5%] 2,250,000 collected | 17/26 domains full | 30,188 short skipped\n","output_type":"stream"},{"name":"stderr","text":"'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01567-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01033-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01251-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00728-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01310-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01062-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01099-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":" [ 96.2%] 2,500,000 collected | 21/26 domains full | 36,081 short skipped\n","output_type":"stream"},{"name":"stderr","text":"'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00931-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01276-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00452-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01276-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01276-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00081-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00240-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01068-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00278-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00424-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01307-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00596-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00064-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'The read operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-00883-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01394-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01020-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01020-of-01683.parquet\nRetrying in 2s [Retry 2/5].\n'_ssl.c:993: The handshake operation timed out' thrown while requesting GET https://huggingface.co/datasets/AdaMLLab/AraMix-domain-classified/resolve/8a88f490e33735f64dd63fa103da1a82c06238a3/minhash_deduped/train-01020-of-01683.parquet\nRetrying in 1s [Retry 1/5].\n","output_type":"stream"},{"name":"stdout","text":"\nAraMix done: 2,600,000 documents collected.\nSkipped (too short) : 38,802\nSkipped (bucket full): 17,818,396\n","output_type":"stream"}],"execution_count":5},{"cell_type":"code","source":"# ── Cell 5: Verify AraMix bucket counts ───────────────────────────────────\n\nprint(f'{\"Domain\":<40} {\"Collected\":>10} {\"Status\":>8}')\nprint('-' * 62)\n\nincomplete = []\nfor domain in ALL_DOMAINS:\n count = bucket_counts[domain]\n status = 'βœ“' if count >= DOCS_PER_DOMAIN else f'⚠ {count:,}'\n print(f'{domain:<40} {count:>10,} {status:>8}')\n if count < DOCS_PER_DOMAIN:\n incomplete.append((domain, count))\n\nprint()\nif incomplete:\n print(f'⚠ {len(incomplete)} domain(s) below target (rare domains β€” expected):')\n for d, c in incomplete:\n print(f' {d}: {c:,} / {DOCS_PER_DOMAIN:,}')\nelse:\n print(f'βœ“ All {NUM_DOMAINS} domains have exactly {DOCS_PER_DOMAIN:,} documents.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-16T00:47:46.982883Z","iopub.execute_input":"2026-06-16T00:47:46.983068Z","iopub.status.idle":"2026-06-16T00:47:46.989215Z","shell.execute_reply.started":"2026-06-16T00:47:46.983052Z","shell.execute_reply":"2026-06-16T00:47:46.988326Z"}},"outputs":[{"name":"stdout","text":"Domain Collected Status\n--------------------------------------------------------------\nAdult 100,000 βœ“\nArts_and_Entertainment 100,000 βœ“\nAutos_and_Vehicles 100,000 βœ“\nBeauty_and_Fitness 100,000 βœ“\nBooks_and_Literature 100,000 βœ“\nBusiness_and_Industrial 100,000 βœ“\nComputers_and_Electronics 100,000 βœ“\nFinance 100,000 βœ“\nFood_and_Drink 100,000 βœ“\nGames 100,000 βœ“\nHealth 100,000 βœ“\nHobbies_and_Leisure 100,000 βœ“\nHome_and_Garden 100,000 βœ“\nInternet_and_Telecom 100,000 βœ“\nJobs_and_Education 100,000 βœ“\nLaw_and_Government 100,000 βœ“\nNews 100,000 βœ“\nOnline_Communities 100,000 βœ“\nPeople_and_Society 100,000 βœ“\nPets_and_Animals 100,000 βœ“\nReal_Estate 100,000 βœ“\nScience 100,000 βœ“\nSensitive_Subjects 100,000 βœ“\nShopping 100,000 βœ“\nSports 100,000 βœ“\nTravel_and_Transportation 100,000 βœ“\n\nβœ“ All 26 domains have exactly 100,000 documents.\n","output_type":"stream"}],"execution_count":6},{"cell_type":"code","source":"# ── Cell 6: Sample Arabic Wikipedia (650K articles) ───────────────────────\n# Wikipedia Arabic 20231101.ar has ~1.2M articles.\n# We sample WIKI_TOTAL (~650K = 53% of it).\n# Wikipedia is entity-dense and relation-rich β€” perfect RE signal for MNTP.\n\nprint(f'Loading Arabic Wikipedia (wikimedia/wikipedia, 20231101.ar)...')\nprint(f'Target: {WIKI_TOTAL:,} articles')\n\nwiki_ds = load_dataset(\n 'wikimedia/wikipedia',\n '20231101.ar',\n split='train',\n streaming=True,\n trust_remote_code=True,\n).shuffle(seed=SEED, buffer_size=50_000)\n\nwiki_rows = []\nwiki_skipped = 0\n\nfor doc in wiki_ds:\n text = doc.get('text', '').strip()\n\n # Wikipedia articles can have very short stubs β€” skip them\n if len(text.split()) < MIN_WORDS:\n wiki_skipped += 1\n continue\n\n wiki_rows.append({\n 'text': text,\n 'domain': 'Wikipedia',\n 'source': 'wikimedia/wikipedia',\n })\n\n if len(wiki_rows) % 100_000 == 0:\n pct = len(wiki_rows) / WIKI_TOTAL * 100\n print(f' [{pct:5.1f}%] {len(wiki_rows):>8,} collected | {wiki_skipped:,} stubs skipped')\n\n if len(wiki_rows) >= WIKI_TOTAL:\n break\n\nprint(f'\\nWikipedia done: {len(wiki_rows):,} articles collected.')\nprint(f'Skipped (stubs < {MIN_WORDS} words): {wiki_skipped:,}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-16T00:48:47.403449Z","iopub.execute_input":"2026-06-16T00:48:47.403697Z","iopub.status.idle":"2026-06-16T00:51:49.906698Z","shell.execute_reply.started":"2026-06-16T00:48:47.403682Z","shell.execute_reply":"2026-06-16T00:51:49.900474Z"}},"outputs":[{"name":"stderr","text":"`trust_remote_code` is not supported anymore.\nPlease check that the Hugging Face dataset 'wikimedia/wikipedia' isn't based on a loading script and remove `trust_remote_code`.\nIf the dataset is based on a loading script, please ask the dataset author to remove it and convert it to a standard format like Parquet.\n","output_type":"stream"},{"name":"stdout","text":"Loading Arabic Wikipedia (wikimedia/wikipedia, 20231101.ar)...\nTarget: 650,000 articles\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"README.md: 0%| | 0.00/131k [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"4a21d72456664496be3911213a3df510"}},"metadata":{}},{"name":"stdout","text":" [ 15.4%] 100,000 collected | 11,126 stubs skipped\n [ 30.8%] 200,000 collected | 21,681 stubs skipped\n [ 46.2%] 300,000 collected | 31,703 stubs skipped\n [ 61.5%] 400,000 collected | 42,870 stubs skipped\n [ 76.9%] 500,000 collected | 53,969 stubs skipped\n [ 92.3%] 600,000 collected | 64,942 stubs skipped\n\nWikipedia done: 650,000 articles collected.\nSkipped (stubs < 30 words): 69,894\n","output_type":"stream"}],"execution_count":7},{"cell_type":"code","source":"# ── Cell 7: Combine β†’ shuffle β†’ train/val split ───────────────────────────\n\nprint('Combining AraMix + Wikipedia...')\nall_rows = aramix_rows + wiki_rows\nprint(f' AraMix : {len(aramix_rows):,}')\nprint(f' Wikipedia : {len(wiki_rows):,}')\nprint(f' Total : {len(all_rows):,}')\n\n# Shuffle before splitting so train/val are not domain-sorted\nprint('\\nShuffling...')\nrandom.shuffle(all_rows)\n\n# Split\nactual_train_size = int(len(all_rows) * TRAIN_RATIO)\ntrain_rows = all_rows[:actual_train_size]\nval_rows = all_rows[actual_train_size:]\n\nprint(f'\\nSplit:')\nprint(f' Train : {len(train_rows):,} ({len(train_rows)/len(all_rows)*100:.1f}%)')\nprint(f' Val : {len(val_rows):,} ({len(val_rows)/len(all_rows)*100:.1f}%)')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-16T00:52:00.895149Z","iopub.execute_input":"2026-06-16T00:52:00.895433Z","iopub.status.idle":"2026-06-16T00:52:02.565252Z","shell.execute_reply.started":"2026-06-16T00:52:00.895417Z","shell.execute_reply":"2026-06-16T00:52:02.564246Z"}},"outputs":[{"name":"stdout","text":"Combining AraMix + Wikipedia...\n AraMix : 2,600,000\n Wikipedia : 650,000\n Total : 3,250,000\n\nShuffling...\n\nSplit:\n Train : 3,185,000 (98.0%)\n Val : 65,000 (2.0%)\n","output_type":"stream"}],"execution_count":8},{"cell_type":"code","source":"# ── Cell 8: Save train.parquet + val.parquet ──────────────────────────────\n\ndef save_parquet(rows, path):\n df = pd.DataFrame(rows)\n df.to_parquet(path, index=False, engine='pyarrow', compression='snappy')\n size_gb = Path(path).stat().st_size / 1e9\n print(f' Saved {len(rows):,} rows β†’ {path} ({size_gb:.2f} GB)')\n return df\n\nprint('Saving...')\ntrain_path = SAVE_DIR / 'train.parquet'\nval_path = SAVE_DIR / 'val.parquet'\n\ntrain_df = save_parquet(train_rows, train_path)\nval_df = save_parquet(val_rows, val_path)\n\n# Save metadata alongside\nmeta = {\n 'aramix_config': ARAMIX_CONFIG,\n 'wiki_subset': '20231101.ar',\n 'docs_per_domain': DOCS_PER_DOMAIN,\n 'num_domains': NUM_DOMAINS,\n 'aramix_total': len(aramix_rows),\n 'wiki_total': len(wiki_rows),\n 'grand_total': len(all_rows),\n 'train_size': len(train_rows),\n 'val_size': len(val_rows),\n 'train_ratio': TRAIN_RATIO,\n 'min_words': MIN_WORDS,\n 'seed': SEED,\n 'domains': ALL_DOMAINS,\n}\nwith open(SAVE_DIR / 'meta.json', 'w', encoding='utf-8') as f:\n json.dump(meta, f, ensure_ascii=False, indent=2)\n\nprint('\\nDone. Files saved:')\nfor p in [train_path, val_path, SAVE_DIR / 'meta.json']:\n print(f' {p}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-16T00:52:08.374502Z","iopub.execute_input":"2026-06-16T00:52:08.374736Z","iopub.status.idle":"2026-06-16T00:53:34.199214Z","shell.execute_reply.started":"2026-06-16T00:52:08.374721Z","shell.execute_reply":"2026-06-16T00:53:34.198031Z"}},"outputs":[{"name":"stdout","text":"Saving...\n Saved 3,185,000 rows β†’ /kaggle/working/train.parquet (6.51 GB)\n Saved 65,000 rows β†’ /kaggle/working/val.parquet (0.13 GB)\n\nDone. Files saved:\n /kaggle/working/train.parquet\n /kaggle/working/val.parquet\n /kaggle/working/meta.json\n","output_type":"stream"}],"execution_count":9},{"cell_type":"code","source":"# ── Cell 9: Sanity check ──────────────────────────────────────────────────\n\nprint('=== TRAIN ===')\nprint(f'Rows : {len(train_df):,}')\nprint(f'Columns: {list(train_df.columns)}')\n\nprint('\\nDomain distribution in train:')\ndomain_dist = train_df['domain'].value_counts()\nfor domain, count in domain_dist.items():\n bar = 'β–ˆ' * int(count / domain_dist.max() * 30)\n print(f' {domain:<35} {count:>8,} {bar}')\n\nprint('\\nSource distribution in train:')\nprint(train_df['source'].value_counts().to_string())\n\ntrain_df['word_count'] = train_df['text'].str.split().str.len()\nprint(f'\\nWord count stats (train):')\nprint(f' Mean : {train_df[\"word_count\"].mean():.0f}')\nprint(f' Median: {train_df[\"word_count\"].median():.0f}')\nprint(f' Min : {train_df[\"word_count\"].min()}')\nprint(f' Max : {train_df[\"word_count\"].max():,}')\nprint(f'\\nEstimated total tokens (Γ—1.3 tok/word):')\nprint(f' Train : {train_df[\"word_count\"].sum() * 1.3 / 1e6:.0f}M')\n\nval_df['word_count'] = val_df['text'].str.split().str.len()\nprint(f' Val : {val_df[\"word_count\"].sum() * 1.3 / 1e6:.0f}M')\n\nprint('\\n=== VAL ===')\nprint(f'Rows : {len(val_df):,}')\nprint('Domain distribution in val:')\nprint(val_df['domain'].value_counts().to_string())\n\nprint('\\nβœ“ All done. Upload /kaggle/working/train.parquet and val.parquet to your dataset.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-16T00:53:34.200044Z","iopub.execute_input":"2026-06-16T00:53:34.200260Z"}},"outputs":[{"name":"stdout","text":"=== TRAIN ===\nRows : 3,185,000\nColumns: ['text', 'domain', 'source']\n\nDomain distribution in train:\n Wikipedia 636,898 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ\n Sensitive_Subjects 98,086 β–ˆβ–ˆβ–ˆβ–ˆ\n Hobbies_and_Leisure 98,082 β–ˆβ–ˆβ–ˆβ–ˆ\n Law_and_Government 98,066 β–ˆβ–ˆβ–ˆβ–ˆ\n Science 98,060 β–ˆβ–ˆβ–ˆβ–ˆ\n People_and_Society 98,045 β–ˆβ–ˆβ–ˆβ–ˆ\n Sports 98,021 β–ˆβ–ˆβ–ˆβ–ˆ\n Real_Estate 98,018 β–ˆβ–ˆβ–ˆβ–ˆ\n Shopping 98,018 β–ˆβ–ˆβ–ˆβ–ˆ\n Business_and_Industrial 98,017 β–ˆβ–ˆβ–ˆβ–ˆ\n Beauty_and_Fitness 98,017 β–ˆβ–ˆβ–ˆβ–ˆ\n News 98,002 β–ˆβ–ˆβ–ˆβ–ˆ\n Adult 98,001 β–ˆβ–ˆβ–ˆβ–ˆ\n Food_and_Drink 98,000 β–ˆβ–ˆβ–ˆβ–ˆ\n Health 97,998 β–ˆβ–ˆβ–ˆβ–ˆ\n Computers_and_Electronics 97,996 β–ˆβ–ˆβ–ˆβ–ˆ\n Autos_and_Vehicles 97,996 β–ˆβ–ˆβ–ˆβ–ˆ\n Pets_and_Animals 97,992 β–ˆβ–ˆβ–ˆβ–ˆ\n Games 97,992 β–ˆβ–ˆβ–ˆβ–ˆ\n Finance 97,992 β–ˆβ–ˆβ–ˆβ–ˆ\n Home_and_Garden 97,986 β–ˆβ–ˆβ–ˆβ–ˆ\n Travel_and_Transportation 97,968 β–ˆβ–ˆβ–ˆβ–ˆ\n Arts_and_Entertainment 97,968 β–ˆβ–ˆβ–ˆβ–ˆ\n Internet_and_Telecom 97,964 β–ˆβ–ˆβ–ˆβ–ˆ\n Jobs_and_Education 97,960 β–ˆβ–ˆβ–ˆβ–ˆ\n Online_Communities 97,934 β–ˆβ–ˆβ–ˆβ–ˆ\n Books_and_Literature 97,923 β–ˆβ–ˆβ–ˆβ–ˆ\n\nSource distribution in train:\nsource\nlightonai/ArabicWeb24 708468\nwikimedia/wikipedia 636898\nHPLT/HPLT2.0_cleaned 499454\nHuggingFaceFW/fineweb-2 465344\nuonlp/CulturaX 454111\nallenai/c4 305080\nClusterlabAi/101_billion_arabic_words_dataset 113686\nHuggingFaceFW/finepdfs 1959\n","output_type":"stream"}],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}
__output__.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [{"stream_name":"stderr","time":4.24407107,"data":"/usr/local/lib/python3.12/dist-packages/mistune.py:435: SyntaxWarning: invalid escape sequence '\\|'\n"}
2
+ ,{"stream_name":"stderr","time":4.24415726,"data":" cells[i][c] = re.sub('\\\\\\\\\\|', '|', cell)\n"}
3
+ ,{"stream_name":"stderr","time":4.775275103,"data":"/usr/local/lib/python3.12/dist-packages/nbconvert/filters/filter_links.py:36: SyntaxWarning: invalid escape sequence '\\_'\n"}
4
+ ,{"stream_name":"stderr","time":4.775366133,"data":" text = re.sub(r'_', '\\_', text) # Escape underscores in display text\n"}
5
+ ,{"stream_name":"stderr","time":6.159286222,"data":"[NbConvertApp] Converting notebook __notebook__.ipynb to html\n"}
6
+ ,{"stream_name":"stderr","time":8.080042824,"data":"[NbConvertApp] Writing 421881 bytes to __results__.html\n"}
7
+ ]
__results__.html ADDED
The diff for this file is too large to render. See raw diff
 
custom.css ADDED
File without changes
meta.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aramix_config": "minhash_deduped",
3
+ "wiki_subset": "20231101.ar",
4
+ "docs_per_domain": 100000,
5
+ "num_domains": 26,
6
+ "aramix_total": 2600000,
7
+ "wiki_total": 650000,
8
+ "grand_total": 3250000,
9
+ "train_size": 3185000,
10
+ "val_size": 65000,
11
+ "train_ratio": 0.98,
12
+ "min_words": 30,
13
+ "seed": 42,
14
+ "domains": [
15
+ "Adult",
16
+ "Arts_and_Entertainment",
17
+ "Autos_and_Vehicles",
18
+ "Beauty_and_Fitness",
19
+ "Books_and_Literature",
20
+ "Business_and_Industrial",
21
+ "Computers_and_Electronics",
22
+ "Finance",
23
+ "Food_and_Drink",
24
+ "Games",
25
+ "Health",
26
+ "Hobbies_and_Leisure",
27
+ "Home_and_Garden",
28
+ "Internet_and_Telecom",
29
+ "Jobs_and_Education",
30
+ "Law_and_Government",
31
+ "News",
32
+ "Online_Communities",
33
+ "People_and_Society",
34
+ "Pets_and_Animals",
35
+ "Real_Estate",
36
+ "Science",
37
+ "Sensitive_Subjects",
38
+ "Shopping",
39
+ "Sports",
40
+ "Travel_and_Transportation"
41
+ ]
42
+ }
train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17e718200cf6d26231e23215fdb87b22dacaca4badd2d9148c00aeab28a7dbda
3
+ size 6510559457
val.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43a777083cb210934beca3ae7076b645cfdf134fa348df6bf5373978b2208368
3
+ size 132463329