File size: 38,480 Bytes
d67f29d
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini","uri":"program://arrow_multitask/module/arrow_phi3_mini#L1-L383","kind":"module","name":"arrow_phi3_mini","path":"arrow_phi3_mini.py","language":"python","start_line":1,"end_line":383,"context_start_line":1,"context_end_line":383,"code":"# Copyright 2025-present the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis script provides a simple evaluation pipeline for multiple-choice reasoning datasets\n(e.g., BoolQ, HellaSwag, ARC, OpenBookQA, Winogrande) with different composition strategies.\n\nUsage examples:\n    python arrow_phi3_mini.py --strategy base --ds_name arc-challenge\n    python arrow_phi3_mini.py --strategy arrow --ds_name boolq\n    python arrow_phi3_mini.py --strategy gks --ds_name hswag\n\nKey features:\n- Supports three strategies:\n\"base\"   → Evaluate the quantized base model directly\n\"arrow\"  → Use Arrow modular routing with task-specific adapters\n\"gks\"    → Use Arrow + GenKnowSub (subtracting general-domain knowledge)\n- Loads evaluation datasets from the Hugging Face Hub\n- Implements a batched evaluation loop that computes per-option likelihoods and selects\n  the answer with the lowest average loss\n- Reports simple accuracy\n\nImplementation details:\n- The base model is quantized to 4-bit using `BitsAndBytesConfig` (nf4, bf16 compute).\n- For Arrow and GKS, task-specific adapters are loaded from the Hugging Face Hub:\n    TahaBa/phi3-mini-clustered-flan/ts_expert_i\n- Task-specific adapters were trained on 10 clusters of FLAN tasks.\n- The clusters were created using Model-Based Clustering (MBC):\n    1. Train a LoRA adapter for each individual task.\n    2. Apply k-means clustering to group tasks based on these adapters.\n    3. Train a LoRA adapter for each resulting cluster.\nFor more details, see the Arrow paper: https://huggingface.co/papers/2405.11157\n\n- For GKS, general adapters are loaded from:\n    TahaBa/phi3-mini-general-adapters/...\n- These adapters were trained on English, French, and German Wikipedia data\n  using a causal language modeling objective with (507-token context → 5-token completion) pairs.\n- This setup encodes general knowledge into the LoRA space, which can then be\n  subtracted from task-specific adapters during inference to isolate and purify them.\nFor more details, see the GenKnowSub paper: https://huggingface.co/papers/2505.10939\n\n- `evaluate_on_multi_choice_batched` handles tokenization, masking context tokens,\n  and computing per-choice log-likelihoods for fair comparison.\n- Accuracy is printed at the end for the selected dataset.\n\nThis script is mainly meant for demonstration purposes and lightweight evaluation,\nnot full-scale benchmarking (batch size / max length can be tuned).\n\n=======================================================================================\n\nResults (evaluated with microsoft/Phi-3-mini-4k-instruct, 4-bit quantization):\n\n| Dataset      | Base Acc. | Arrow Acc. | Arrow+GKS Acc. |\n|--------------|-----------|------------|----------------|\n| ARC-Challenge|   0.4515  |   0.5418   |     0.5585     |\n| ARC-Easy     |   0.6894  |   0.8404   |     0.8473     |\n| Winogrande   |   0.5769  |   0.6550   |     0.6724     |\n| BoolQ        |   0.8146  |   0.8030   |     0.8247     |\n| OpenBookQA   |   0.43    |   0.448    |     0.472      |\n| HellaSwag    |   0.7318  |   0.7150   |     0.7376     |\n\nObservations:\n- Arrow generally improves over the base model by routing tokens to the most relevant task adapters.\n- Applying GKS (general knowledge subtraction) consistently gives further gains compared to Arrow and Base.\n\nThese numbers are not meant as leaderboard results, but as a sanity check\nto verify that the implementation works as expected and demonstrates\nthe benefits of Arrow and GenKnowSub.\n\"\"\"\n\nimport argparse\nimport random\n\nimport numpy as np\nimport torch\nfrom datasets import load_dataset\nfrom sklearn.metrics import accuracy_score\nfrom tqdm import tqdm\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nfrom peft import ArrowConfig, create_arrow_model\n\n\nMODEL_NAME = \"microsoft/Phi-3-mini-4k-instruct\"\nMODEL_MAX_LEN = 2048\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(description=\"Training script with strategy selection\")\n\n    parser.add_argument(\n        \"--strategy\",\n        type=str,\n        choices=[\"base\", \"arrow\", \"gks\"],\n        default=\"base\",\n        help=\"Training strategy to use: base, arrow, or gks\",\n    )\n    parser.add_argument(\n        \"--ds_name\",\n        type=str,\n        choices=[\"boolq\", \"hswag\", \"arc-easy\", \"arc-challenge\", \"oqa\", \"wg\"],\n        default=\"arc-challenge\",\n        help=\"Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg\",\n    )\n\n    return parser.parse_args()\n\n\ndef read_test_dataset(ds_name):\n    if ds_name == \"boolq\":\n        ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"hswag\":\n        ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-challenge\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-easy\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"oqa\":\n        ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"wg\":\n        ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n    else:\n        raise f\"Dataset {ds_name} is not supported yet.\"\n\n    return ds\n\n\ndef extract_input_content(ds_name, row):\n    if ds_name == \"boolq\":\n        return f\"[passage]{row['passage']}[question]{row['question']}\"\n    if ds_name == \"hswag\":\n        return row[\"ctx\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"question\"]\n    if ds_name == \"oqa\":\n        return row[\"question_stem\"]\n    if ds_name == \"wg\":\n        return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n    options_texts = []\n    content = extract_input_content(ds_name, row)\n    if ds_name == \"boolq\":\n        choices = [\"true\", \"false\"]\n    if ds_name == \"hswag\":\n        choices = row[\"endings\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        choices = row[\"choices\"][\"text\"]\n    if ds_name == \"wg\":\n        choices = [row[\"option1\"], row[\"option2\"]]\n    if ds_name == \"oqa\":\n        choices = row[\"choices\"][\"text\"]\n\n    for choice in choices:\n        options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n    return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n    if ds_name == \"boolq\":\n        return 0 if row[\"answer\"] is True else 1\n    if ds_name == \"hswag\":\n        return int(row[\"label\"])\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n    if ds_name == \"wg\":\n        return int(row[\"answer\"]) - 1\n    if ds_name == \"oqa\":\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n    elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n        torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n    bs = logits.size(0)\n    vocab_size = logits.size(-1)\n    labels = labels.squeeze(-1)\n    shift_logits = logits[..., :-1, :].contiguous()\n    shift_labels = labels[..., 1:].contiguous()\n\n    # Flatten the tokens\n    loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n    shift_logits = shift_logits.view(-1, vocab_size)\n    shift_labels = shift_labels.view(-1)\n\n    shift_labels = shift_labels.to(shift_logits.device)\n    loss = loss_fct(shift_logits, shift_labels)\n\n    # reshape back\n    if reduction == \"none\":\n        loss = loss.view((bs, -1))\n        non_zero_loss = (loss != 0).sum(dim=-1)\n        non_zero_loss[non_zero_loss == 0] = 1\n        loss = loss.sum(dim=-1) / non_zero_loss\n\n    return loss.float()  # Convert to float32 before returning\n\n\ndef evaluate_on_multi_choice_batched(\n    eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device=\"auto\"\n):\n    # Local import to mirror your original function\n    model.eval()\n\n    if device == \"auto\":\n        device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n    else:\n        device = torch.device(device)\n\n    for start in tqdm(\n        range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size\n    ):\n        rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]\n\n        # Build the flattened option texts for this batch\n        all_texts = []\n        options_per_sample = []  # number of options for each sample\n        ctx_lens_per_option = []  # context length replicated per option\n\n        for row in rows:\n            # options: [\"<|user|>...<|assistant|>choiceA<|end|>\", ...]\n            options = create_multi_choice_options(row, ds_name)\n            options_per_sample.append(len(options))\n\n            # compute context length once per sample (align with your -1 shift)\n            content = extract_input_content(ds_name, row)\n            context_prompt = f\"<|user|>\\n{content}<|end|>\\n<|assistant|>\"\n            ctx_len = len(tokenizer.encode(context_prompt)) - 1\n\n            all_texts.extend(options)\n            ctx_lens_per_option.extend([ctx_len] * len(options))\n\n            # collect gold label\n            labels.append(extract_multi_choice_target_index(row, ds_name))\n\n        # Tokenize all options in one go\n        tokenized = tokenizer(\n            all_texts,\n            return_tensors=\"pt\",\n            padding=True,\n            truncation=True,\n            max_length=max_length,\n        )\n        tokenized = {k: v.to(device) for k, v in tokenized.items()}\n\n        # Create masked labels: ignore context and padding\n        masked_labels = tokenized[\"input_ids\"].clone()\n        for i, ctx_len in enumerate(ctx_lens_per_option):\n            masked_labels[i, :ctx_len] = -100\n        masked_labels[tokenized[\"attention_mask\"] == 0] = -100\n\n        with torch.no_grad():\n            logits = model(input_ids=tokenized[\"input_ids\"], attention_mask=tokenized[\"attention_mask\"]).logits\n            # per-sequence losses\n            losses = compute_loglike_loss(logits, masked_labels, reduction=\"none\").detach().cpu()\n\n        # Reduce per sample (argmin across its options)\n        idx = 0\n        for n_opt in options_per_sample:\n            pred = torch.argmin(losses[idx : idx + n_opt]).item()\n            predictions.append(pred)\n            idx += n_opt\n\n    print(\n        f\"Accuracy for dataset {args.ds_name} and strategy {args.strategy} is: {accuracy_score(labels, predictions)}\"\n    )\n\n\nif __name__ == \"__main__\":\n    args = parse_args()\n    print(f\"Selected strategy: {args.strategy}\")\n    print(f\"Dataset name: {args.ds_name}\")\n\n    # Loading the tokeniser\n    tokenizer = AutoTokenizer.from_pretrained(\n        MODEL_NAME,\n        use_fast=True,\n        padding_side=\"right\",\n        model_max_length=MODEL_MAX_LEN,\n    )\n\n    # Quantisation config\n    bnb_config = BitsAndBytesConfig(\n        load_in_4bit=True,\n        bnb_4bit_quant_type=\"nf4\",\n        bnb_4bit_compute_dtype=torch.bfloat16,\n        bnb_4bit_use_double_quant=False,\n    )\n\n    # Loading the model\n    base_model = AutoModelForCausalLM.from_pretrained(\n        MODEL_NAME,\n        dtype=torch.bfloat16,\n        device_map=\"auto\",\n        quantization_config=bnb_config,\n    )\n\n    # Loading the test dataset\n    test_dataset = read_test_dataset(args.ds_name)\n    print(f\"{args.ds_name} is loaded with size: {len(test_dataset)}.\")\n\n    labels, predictions = [], []\n    if args.strategy == \"base\":\n        # Batch-wise inference\n        with torch.no_grad():\n            evaluate_on_multi_choice_batched(\n                test_dataset,\n                base_model,\n                tokenizer,\n                args.ds_name,\n                labels,\n                predictions,\n                args,\n                batch_size=64,  # tune this\n                max_length=512,  # tune if options are long\n                device=\"auto\",\n            )\n    else:\n        general_adapter_paths = []\n        if args.strategy == \"gks\":\n            arrow_config = ArrowConfig(\n                top_k=3,\n                router_temperature=1.0,\n                use_gks=True,\n            )\n            # General adapter paths from the hub\n            general_adapter_paths = [\n                \"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langen/checkpoint-17\",\n                \"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langfr/checkpoint-35\",\n                \"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langger/checkpoint-17\",\n            ]\n        else:\n            arrow_config = ArrowConfig(\n                top_k=3,\n                router_temperature=1.0,\n            )\n\n        # Task-specific adapter paths from the hub\n        task_specific_adapter_paths = [f\"TahaBa/phi3-mini-clustered-flan/ts_expert_{i}\" for i in range(10)]\n\n        # Creating the Arrow model\n        model = create_arrow_model(\n            base_model=base_model,\n            task_specific_adapter_paths=task_specific_adapter_paths,\n            general_adapter_paths=general_adapter_paths,\n            arrow_config=arrow_config,\n        )\n\n        # Batch-wise inference\n        with torch.no_grad():\n            evaluate_on_multi_choice_batched(\n                test_dataset,\n                model,\n                tokenizer,\n                args.ds_name,\n                labels,\n                predictions,\n                args,\n                batch_size=32,  # tune this\n                max_length=512,  # tune if options are long\n                device=\"auto\",\n            )","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.parse_args","uri":"program://arrow_multitask/function/arrow_phi3_mini.parse_args#L99-L117","kind":"function","name":"parse_args","path":"arrow_phi3_mini.py","language":"python","start_line":99,"end_line":117,"context_start_line":79,"context_end_line":137,"code":"the benefits of Arrow and GenKnowSub.\n\"\"\"\n\nimport argparse\nimport random\n\nimport numpy as np\nimport torch\nfrom datasets import load_dataset\nfrom sklearn.metrics import accuracy_score\nfrom tqdm import tqdm\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nfrom peft import ArrowConfig, create_arrow_model\n\n\nMODEL_NAME = \"microsoft/Phi-3-mini-4k-instruct\"\nMODEL_MAX_LEN = 2048\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(description=\"Training script with strategy selection\")\n\n    parser.add_argument(\n        \"--strategy\",\n        type=str,\n        choices=[\"base\", \"arrow\", \"gks\"],\n        default=\"base\",\n        help=\"Training strategy to use: base, arrow, or gks\",\n    )\n    parser.add_argument(\n        \"--ds_name\",\n        type=str,\n        choices=[\"boolq\", \"hswag\", \"arc-easy\", \"arc-challenge\", \"oqa\", \"wg\"],\n        default=\"arc-challenge\",\n        help=\"Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg\",\n    )\n\n    return parser.parse_args()\n\n\ndef read_test_dataset(ds_name):\n    if ds_name == \"boolq\":\n        ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"hswag\":\n        ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-challenge\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-easy\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"oqa\":\n        ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"wg\":\n        ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n    else:\n        raise f\"Dataset {ds_name} is not supported yet.\"\n\n    return ds\n","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.read_test_dataset","uri":"program://arrow_multitask/function/arrow_phi3_mini.read_test_dataset#L120-L136","kind":"function","name":"read_test_dataset","path":"arrow_phi3_mini.py","language":"python","start_line":120,"end_line":136,"context_start_line":100,"context_end_line":156,"code":"    parser = argparse.ArgumentParser(description=\"Training script with strategy selection\")\n\n    parser.add_argument(\n        \"--strategy\",\n        type=str,\n        choices=[\"base\", \"arrow\", \"gks\"],\n        default=\"base\",\n        help=\"Training strategy to use: base, arrow, or gks\",\n    )\n    parser.add_argument(\n        \"--ds_name\",\n        type=str,\n        choices=[\"boolq\", \"hswag\", \"arc-easy\", \"arc-challenge\", \"oqa\", \"wg\"],\n        default=\"arc-challenge\",\n        help=\"Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg\",\n    )\n\n    return parser.parse_args()\n\n\ndef read_test_dataset(ds_name):\n    if ds_name == \"boolq\":\n        ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"hswag\":\n        ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-challenge\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-easy\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"oqa\":\n        ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"wg\":\n        ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n    else:\n        raise f\"Dataset {ds_name} is not supported yet.\"\n\n    return ds\n\n\ndef extract_input_content(ds_name, row):\n    if ds_name == \"boolq\":\n        return f\"[passage]{row['passage']}[question]{row['question']}\"\n    if ds_name == \"hswag\":\n        return row[\"ctx\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"question\"]\n    if ds_name == \"oqa\":\n        return row[\"question_stem\"]\n    if ds_name == \"wg\":\n        return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n    options_texts = []\n    content = extract_input_content(ds_name, row)\n    if ds_name == \"boolq\":\n        choices = [\"true\", \"false\"]","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.extract_input_content","uri":"program://arrow_multitask/function/arrow_phi3_mini.extract_input_content#L139-L149","kind":"function","name":"extract_input_content","path":"arrow_phi3_mini.py","language":"python","start_line":139,"end_line":149,"context_start_line":119,"context_end_line":169,"code":"\ndef read_test_dataset(ds_name):\n    if ds_name == \"boolq\":\n        ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"hswag\":\n        ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-challenge\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"arc-easy\":\n        ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"oqa\":\n        ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n    elif ds_name == \"wg\":\n        ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n    else:\n        raise f\"Dataset {ds_name} is not supported yet.\"\n\n    return ds\n\n\ndef extract_input_content(ds_name, row):\n    if ds_name == \"boolq\":\n        return f\"[passage]{row['passage']}[question]{row['question']}\"\n    if ds_name == \"hswag\":\n        return row[\"ctx\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"question\"]\n    if ds_name == \"oqa\":\n        return row[\"question_stem\"]\n    if ds_name == \"wg\":\n        return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n    options_texts = []\n    content = extract_input_content(ds_name, row)\n    if ds_name == \"boolq\":\n        choices = [\"true\", \"false\"]\n    if ds_name == \"hswag\":\n        choices = row[\"endings\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        choices = row[\"choices\"][\"text\"]\n    if ds_name == \"wg\":\n        choices = [row[\"option1\"], row[\"option2\"]]\n    if ds_name == \"oqa\":\n        choices = row[\"choices\"][\"text\"]\n\n    for choice in choices:\n        options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n    return options_texts","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.create_multi_choice_options","uri":"program://arrow_multitask/function/arrow_phi3_mini.create_multi_choice_options#L152-L169","kind":"function","name":"create_multi_choice_options","path":"arrow_phi3_mini.py","language":"python","start_line":152,"end_line":169,"context_start_line":132,"context_end_line":189,"code":"        ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n    else:\n        raise f\"Dataset {ds_name} is not supported yet.\"\n\n    return ds\n\n\ndef extract_input_content(ds_name, row):\n    if ds_name == \"boolq\":\n        return f\"[passage]{row['passage']}[question]{row['question']}\"\n    if ds_name == \"hswag\":\n        return row[\"ctx\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"question\"]\n    if ds_name == \"oqa\":\n        return row[\"question_stem\"]\n    if ds_name == \"wg\":\n        return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n    options_texts = []\n    content = extract_input_content(ds_name, row)\n    if ds_name == \"boolq\":\n        choices = [\"true\", \"false\"]\n    if ds_name == \"hswag\":\n        choices = row[\"endings\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        choices = row[\"choices\"][\"text\"]\n    if ds_name == \"wg\":\n        choices = [row[\"option1\"], row[\"option2\"]]\n    if ds_name == \"oqa\":\n        choices = row[\"choices\"][\"text\"]\n\n    for choice in choices:\n        options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n    return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n    if ds_name == \"boolq\":\n        return 0 if row[\"answer\"] is True else 1\n    if ds_name == \"hswag\":\n        return int(row[\"label\"])\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n    if ds_name == \"wg\":\n        return int(row[\"answer\"]) - 1\n    if ds_name == \"oqa\":\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.extract_multi_choice_target_index","uri":"program://arrow_multitask/function/arrow_phi3_mini.extract_multi_choice_target_index#L172-L182","kind":"function","name":"extract_multi_choice_target_index","path":"arrow_phi3_mini.py","language":"python","start_line":172,"end_line":182,"context_start_line":152,"context_end_line":202,"code":"def create_multi_choice_options(row, ds_name):\n    options_texts = []\n    content = extract_input_content(ds_name, row)\n    if ds_name == \"boolq\":\n        choices = [\"true\", \"false\"]\n    if ds_name == \"hswag\":\n        choices = row[\"endings\"]\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        choices = row[\"choices\"][\"text\"]\n    if ds_name == \"wg\":\n        choices = [row[\"option1\"], row[\"option2\"]]\n    if ds_name == \"oqa\":\n        choices = row[\"choices\"][\"text\"]\n\n    for choice in choices:\n        options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n    return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n    if ds_name == \"boolq\":\n        return 0 if row[\"answer\"] is True else 1\n    if ds_name == \"hswag\":\n        return int(row[\"label\"])\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n    if ds_name == \"wg\":\n        return int(row[\"answer\"]) - 1\n    if ds_name == \"oqa\":\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n    elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n        torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n    bs = logits.size(0)\n    vocab_size = logits.size(-1)\n    labels = labels.squeeze(-1)\n    shift_logits = logits[..., :-1, :].contiguous()\n    shift_labels = labels[..., 1:].contiguous()\n\n    # Flatten the tokens","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.set_seed","uri":"program://arrow_multitask/function/arrow_phi3_mini.set_seed#L185-L192","kind":"function","name":"set_seed","path":"arrow_phi3_mini.py","language":"python","start_line":185,"end_line":192,"context_start_line":165,"context_end_line":212,"code":"\n    for choice in choices:\n        options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n    return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n    if ds_name == \"boolq\":\n        return 0 if row[\"answer\"] is True else 1\n    if ds_name == \"hswag\":\n        return int(row[\"label\"])\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n    if ds_name == \"wg\":\n        return int(row[\"answer\"]) - 1\n    if ds_name == \"oqa\":\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n    elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n        torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n    bs = logits.size(0)\n    vocab_size = logits.size(-1)\n    labels = labels.squeeze(-1)\n    shift_logits = logits[..., :-1, :].contiguous()\n    shift_labels = labels[..., 1:].contiguous()\n\n    # Flatten the tokens\n    loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n    shift_logits = shift_logits.view(-1, vocab_size)\n    shift_labels = shift_labels.view(-1)\n\n    shift_labels = shift_labels.to(shift_logits.device)\n    loss = loss_fct(shift_logits, shift_labels)\n\n    # reshape back\n    if reduction == \"none\":\n        loss = loss.view((bs, -1))","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.compute_loglike_loss","uri":"program://arrow_multitask/function/arrow_phi3_mini.compute_loglike_loss#L195-L217","kind":"function","name":"compute_loglike_loss","path":"arrow_phi3_mini.py","language":"python","start_line":195,"end_line":217,"context_start_line":175,"context_end_line":237,"code":"    if ds_name == \"hswag\":\n        return int(row[\"label\"])\n    if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n    if ds_name == \"wg\":\n        return int(row[\"answer\"]) - 1\n    if ds_name == \"oqa\":\n        return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n    elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n        torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n    bs = logits.size(0)\n    vocab_size = logits.size(-1)\n    labels = labels.squeeze(-1)\n    shift_logits = logits[..., :-1, :].contiguous()\n    shift_labels = labels[..., 1:].contiguous()\n\n    # Flatten the tokens\n    loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n    shift_logits = shift_logits.view(-1, vocab_size)\n    shift_labels = shift_labels.view(-1)\n\n    shift_labels = shift_labels.to(shift_logits.device)\n    loss = loss_fct(shift_logits, shift_labels)\n\n    # reshape back\n    if reduction == \"none\":\n        loss = loss.view((bs, -1))\n        non_zero_loss = (loss != 0).sum(dim=-1)\n        non_zero_loss[non_zero_loss == 0] = 1\n        loss = loss.sum(dim=-1) / non_zero_loss\n\n    return loss.float()  # Convert to float32 before returning\n\n\ndef evaluate_on_multi_choice_batched(\n    eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device=\"auto\"\n):\n    # Local import to mirror your original function\n    model.eval()\n\n    if device == \"auto\":\n        device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n    else:\n        device = torch.device(device)\n\n    for start in tqdm(\n        range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size\n    ):\n        rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]\n\n        # Build the flattened option texts for this batch\n        all_texts = []","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.evaluate_on_multi_choice_batched","uri":"program://arrow_multitask/function/arrow_phi3_mini.evaluate_on_multi_choice_batched#L220-L287","kind":"function","name":"evaluate_on_multi_choice_batched","path":"arrow_phi3_mini.py","language":"python","start_line":220,"end_line":287,"context_start_line":200,"context_end_line":307,"code":"    shift_labels = labels[..., 1:].contiguous()\n\n    # Flatten the tokens\n    loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n    shift_logits = shift_logits.view(-1, vocab_size)\n    shift_labels = shift_labels.view(-1)\n\n    shift_labels = shift_labels.to(shift_logits.device)\n    loss = loss_fct(shift_logits, shift_labels)\n\n    # reshape back\n    if reduction == \"none\":\n        loss = loss.view((bs, -1))\n        non_zero_loss = (loss != 0).sum(dim=-1)\n        non_zero_loss[non_zero_loss == 0] = 1\n        loss = loss.sum(dim=-1) / non_zero_loss\n\n    return loss.float()  # Convert to float32 before returning\n\n\ndef evaluate_on_multi_choice_batched(\n    eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device=\"auto\"\n):\n    # Local import to mirror your original function\n    model.eval()\n\n    if device == \"auto\":\n        device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n    else:\n        device = torch.device(device)\n\n    for start in tqdm(\n        range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size\n    ):\n        rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]\n\n        # Build the flattened option texts for this batch\n        all_texts = []\n        options_per_sample = []  # number of options for each sample\n        ctx_lens_per_option = []  # context length replicated per option\n\n        for row in rows:\n            # options: [\"<|user|>...<|assistant|>choiceA<|end|>\", ...]\n            options = create_multi_choice_options(row, ds_name)\n            options_per_sample.append(len(options))\n\n            # compute context length once per sample (align with your -1 shift)\n            content = extract_input_content(ds_name, row)\n            context_prompt = f\"<|user|>\\n{content}<|end|>\\n<|assistant|>\"\n            ctx_len = len(tokenizer.encode(context_prompt)) - 1\n\n            all_texts.extend(options)\n            ctx_lens_per_option.extend([ctx_len] * len(options))\n\n            # collect gold label\n            labels.append(extract_multi_choice_target_index(row, ds_name))\n\n        # Tokenize all options in one go\n        tokenized = tokenizer(\n            all_texts,\n            return_tensors=\"pt\",\n            padding=True,\n            truncation=True,\n            max_length=max_length,\n        )\n        tokenized = {k: v.to(device) for k, v in tokenized.items()}\n\n        # Create masked labels: ignore context and padding\n        masked_labels = tokenized[\"input_ids\"].clone()\n        for i, ctx_len in enumerate(ctx_lens_per_option):\n            masked_labels[i, :ctx_len] = -100\n        masked_labels[tokenized[\"attention_mask\"] == 0] = -100\n\n        with torch.no_grad():\n            logits = model(input_ids=tokenized[\"input_ids\"], attention_mask=tokenized[\"attention_mask\"]).logits\n            # per-sequence losses\n            losses = compute_loglike_loss(logits, masked_labels, reduction=\"none\").detach().cpu()\n\n        # Reduce per sample (argmin across its options)\n        idx = 0\n        for n_opt in options_per_sample:\n            pred = torch.argmin(losses[idx : idx + n_opt]).item()\n            predictions.append(pred)\n            idx += n_opt\n\n    print(\n        f\"Accuracy for dataset {args.ds_name} and strategy {args.strategy} is: {accuracy_score(labels, predictions)}\"\n    )\n\n\nif __name__ == \"__main__\":\n    args = parse_args()\n    print(f\"Selected strategy: {args.strategy}\")\n    print(f\"Dataset name: {args.ds_name}\")\n\n    # Loading the tokeniser\n    tokenizer = AutoTokenizer.from_pretrained(\n        MODEL_NAME,\n        use_fast=True,\n        padding_side=\"right\",\n        model_max_length=MODEL_MAX_LEN,\n    )\n\n    # Quantisation config\n    bnb_config = BitsAndBytesConfig(\n        load_in_4bit=True,\n        bnb_4bit_quant_type=\"nf4\",\n        bnb_4bit_compute_dtype=torch.bfloat16,","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
{"repo_id":"arrow_multitask","entity_id":"file:arrow_phi3_mini.py","uri":"program://arrow_multitask/file/arrow_phi3_mini.py","kind":"file","name":"arrow_phi3_mini.py","path":"arrow_phi3_mini.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright 2025-present the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis script provides a simple evaluation pipeline for multiple-choice reasoning datasets\n(e.g., BoolQ, HellaSwag, ARC, OpenBookQA, Winogrande) with different composition strategies.\n\nUsage examples:\n    python arrow_phi3_mini.py --strategy base --ds_name arc-challenge\n    python arrow_phi3_mini.py --strategy arrow --ds_name boolq","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}