{"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= 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:0010} {\"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:008,} {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}]}