File size: 62,975 Bytes
6030462 | 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}]} |