{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaL4","dataSources":[{"sourceId":84795,"databundleVersionId":10934030,"sourceType":"competition"},{"sourceId":221096520,"sourceType":"kernelVersion"},{"sourceId":236932,"sourceType":"modelInstanceVersion","modelInstanceId":202348,"modelId":224071}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"papermill":{"default_parameters":{},"duration":22.341371,"end_time":"2024-12-11T03:22:13.479076","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-12-11T03:21:51.137705","version":"2.6.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\n# https://www.kaggle.com/competitions/ai-mathematical-olympiad-progress-prize-2/discussion/560682#3113134\nos.environ[\"TRITON_PTXAS_PATH\"] = \"/usr/local/cuda/bin/ptxas\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:15:49.409902Z","iopub.execute_input":"2025-02-10T23:15:49.410123Z","iopub.status.idle":"2025-02-10T23:15:49.412954Z","shell.execute_reply.started":"2025-02-10T23:15:49.410103Z","shell.execute_reply":"2025-02-10T23:15:49.412385Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import io\nimport os\nimport shutil\n\nimport pandas as pd\nimport polars as pl\n\nimport kaggle_evaluation.konwinski_prize_inference_server","metadata":{"trusted":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-02-10T23:15:49.413457Z","iopub.execute_input":"2025-02-10T23:15:49.413638Z","iopub.status.idle":"2025-02-10T23:16:01.275695Z","shell.execute_reply.started":"2025-02-10T23:15:49.413621Z","shell.execute_reply":"2025-02-10T23:16:01.275031Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"The evaluation API requires that you set up a server which will respond to inference requests. We have already defined the server; you just need write the predict function. When we evaluate your submission on the hidden test set the client defined in `konwinski_prize_gateway` will run in a different container with direct access to the hidden test set and hand off the data.\n\nYour code will always have access to the published copies of the files.","metadata":{"papermill":{"duration":0.002032,"end_time":"2024-12-11T03:22:08.823897","exception":false,"start_time":"2024-12-11T03:22:08.821865","status":"completed"},"tags":[]}},{"cell_type":"code","source":"instance_count = None\n\ndef get_number_of_instances(num_instances: int) -> None:\n    \"\"\" The very first message from the gateway will be the total number of instances to be served.\n    You don't need to edit this function.\n    \"\"\"\n    global instance_count\n    instance_count = num_instances","metadata":{"papermill":{"duration":0.011949,"end_time":"2024-12-11T03:22:08.838279","exception":false,"start_time":"2024-12-11T03:22:08.82633","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:16:01.276333Z","iopub.execute_input":"2025-02-10T23:16:01.276913Z","iopub.status.idle":"2025-02-10T23:16:01.280299Z","shell.execute_reply.started":"2025-02-10T23:16:01.276889Z","shell.execute_reply":"2025-02-10T23:16:01.279687Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Initialize LLM","metadata":{}},{"cell_type":"code","source":"from vllm import LLM, SamplingParams\nimport warnings\n\nwarnings.simplefilter('ignore')\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1,2,3\"\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\nif os.getenv('KAGGLE_KERNEL_RUN_TYPE') or os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    llm_model_pth = '/kaggle/input/m/shelterw/deepseek-r1/transformers/deepseek-r1-distill-qwen-32b-awq/1'\nelse:\n    llm_model_pth = '/root/volume/KirillR/QwQ-32B-Preview-AWQ'\n\nMAX_NUM_SEQS = 1\nMAX_MODEL_LEN = 32_768\nMAX_TOKENS = 8192\n\nllm = LLM(\n    llm_model_pth,\n    # dtype=\"half\",               # The data type for the model weights and activations\n    max_num_seqs=MAX_NUM_SEQS,   # Maximum number of sequences per iteration. Default is 256\n    max_model_len=MAX_MODEL_LEN, # Model context length\n    trust_remote_code=True,      # Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer\n    tensor_parallel_size=4,      # The number of GPUs to use for distributed execution with tensor parallelism\n    gpu_memory_utilization=0.95, # The ratio (between 0 and 1) of GPU memory to reserve for the model\n    seed=2025,\n)","metadata":{"trusted":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-02-10T23:16:01.280898Z","iopub.execute_input":"2025-02-10T23:16:01.281119Z","iopub.status.idle":"2025-02-10T23:20:47.836683Z","shell.execute_reply.started":"2025-02-10T23:16:01.281099Z","shell.execute_reply":"2025-02-10T23:20:47.835887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tokenizer = llm.get_tokenizer()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.837713Z","iopub.execute_input":"2025-02-10T23:20:47.837971Z","iopub.status.idle":"2025-02-10T23:20:47.841132Z","shell.execute_reply.started":"2025-02-10T23:20:47.837929Z","shell.execute_reply":"2025-02-10T23:20:47.840491Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Helper functions","metadata":{}},{"cell_type":"code","source":"import os\n\ndef stringify_directory(directory):\n    full_paths = []\n    \n    rel_path_start = len(directory) + 1  # +1 for the trailing slash\n    for root, dirs, files in os.walk(directory):\n        for file in files:\n            full_path = os.path.join(root, file)\n            full_paths.append(full_path)\n    return \"\\n\".join(full_paths)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.843082Z","iopub.execute_input":"2025-02-10T23:20:47.843311Z","iopub.status.idle":"2025-02-10T23:20:47.8586Z","shell.execute_reply.started":"2025-02-10T23:20:47.843292Z","shell.execute_reply":"2025-02-10T23:20:47.85801Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import re\n\n\ndef extract_file_query(xml_content):\n    import xml.etree.ElementTree as ET\n\n    # Prepare a data structure to collect results\n    parsed_data = {}\n    pattern = r'<root>(.*?)</root>'\n    matches = re.findall(pattern, xml_content, re.DOTALL)\n    \n    for match in matches:\n        try:\n            # Parse the XML\n            root = ET.fromstring(\"<root>\" + match + \"</root>\")\n            \n            # Find all <entry> elements\n            for entry in root.findall(\"entry\"):\n                # Extract the <filepath> text\n                filepath = entry.find(\"filepath\")\n                filepath_text = filepath.text.strip() if filepath is not None else None\n            \n                # Locate <strings_to_search> container\n                strings_container = entry.find(\"strings_to_search\")\n                \n                # Gather each <string_to_search> text\n                search_strings = []\n                if strings_container is not None:\n                    for s in strings_container.findall(\"string_to_search\"):\n                        if s.text is not None:\n                            search_strings.append(s.text.strip())\n                \n                # Store in a dictionary: { filepath: [search_strings...] }\n                parsed_data[filepath_text] = search_strings\n        except:\n            print(\"Error parsing output\", xml_content)\n            return \"\"\n        \n    return parsed_data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.859795Z","iopub.execute_input":"2025-02-10T23:20:47.860051Z","iopub.status.idle":"2025-02-10T23:20:47.872368Z","shell.execute_reply.started":"2025-02-10T23:20:47.86003Z","shell.execute_reply":"2025-02-10T23:20:47.871596Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"reading_prompt = \"\"\"\nYou will be implementing a git diff patch to solve an issue with the code repository.\nYou will first need to select files in the file directory.\n\nThis is the problem statement.\n\n{problem_statement}\n\nThis is the file directory\n\n<directory>\n{directory_string}\n</directory>\n\nWhich files should be inspected so that we can solve the problem?\nWhen we inspect each file, what strings should be searched?\n\nReturn the strings to search in this format\n\n(explanation)\n\n<root>\n    <entry>\n        <filepath>filepath</filepath>  \n        <strings_to_search>\n            <string_to_search>string_to_search</string_to_search>\n            ...\n            <string_to_search>string_to_search</string_to_search>\n        </strings_to_search>\n    </entry>\n</root>\n\n(explanation)\n\n<root>\n    <entry>\n        <filepath>filepath</filepath>\n        <strings_to_search>\n            <string_to_search>string_to_search</string_to_search>\n            ...\n            <string_to_search>string_to_search</string_to_search>\n        </strings_to_search>\n    </entry>\n</root>\n...\n\nNotes:\n- Make sure to encode each entry between <root> and </root>\n- Return the FULL filepath - exactly as specified in <directory> and </directory>\n    - Example: repo/path/to/directory/file.py\n- If you are searching for a word instead of a substring, maybe add spaces or brackets before and after the string\n    For example, if you are searching for uses of the function `calculate`, use ` calculate(` as the search string instead\n- Prefer searching longer strings\n- Do not inspect more than 5 files\n- Only inspect the necessary files\n\"\"\".strip()\n\n\ndef get_file_query(directory_string, problem_statement):\n\n    sampling_params = SamplingParams(\n        temperature=1.0,              # randomness of the sampling\n        min_p=0.01,\n        skip_special_tokens=True,     # Whether to skip special tokens in the output\n        max_tokens=MAX_MODEL_LEN,\n    )\n    \n    list_of_messages = [\n        [\n            {\n                \"role\": \"user\",\n                \"content\": reading_prompt.format(\n                    problem_statement=problem_statement,\n                    directory_string=directory_string,\n                )\n            },\n        ]\n    ]\n\n    list_of_texts = [\n        tokenizer.apply_chat_template(\n            conversation=messages,\n            tokenize=False,\n            add_generation_prompt=True\n        )\n        for messages in list_of_messages\n    ]\n    # print(list_of_texts)\n    print([len(tokenizer.encode(text)) for text in list_of_texts])\n\n    request_output = llm.generate(prompts=list_of_texts, sampling_params=sampling_params)\n    if not request_output:\n        return \"\", \"\"\n    response_text = request_output[0].outputs[0].text\n    file_query = extract_file_query(response_text)\n    return file_query, response_text","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.873028Z","iopub.execute_input":"2025-02-10T23:20:47.873242Z","iopub.status.idle":"2025-02-10T23:20:47.883771Z","shell.execute_reply.started":"2025-02-10T23:20:47.873224Z","shell.execute_reply":"2025-02-10T23:20:47.883193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"REPO_PATH = \"repo\"\n\ndef fetch_file_contents(files_to_search, context_lines=10, max_gap=0):\n    from io import StringIO\n\n    def find_lines_in_files_with_context(search_map, context_lines=context_lines):\n        \"\"\"\n        Given a dictionary mapping file paths to a list of search terms,\n        open each file and gather *snippets* of lines that contain any\n        of those search terms, including 'context_lines' before and after.\n\n        Returns a list of lists:\n        [\n          [  # For file1\n             [ (line_number, text), (line_number, text), ... ],\n             [ ... ],\n          ],\n          [  # For file2\n             ...\n          ],\n          ...\n        ]\n        \"\"\"\n        all_matches_per_file = []\n\n        for path, terms in search_map.items():\n            if not os.path.isfile(path):\n                # If the file is not found, record an empty list\n                all_matches_per_file.append([])\n                continue\n\n            with open(path, \"r\", encoding=\"utf-8\", errors=\"replace\") as f:\n                lines = f.readlines()\n\n            file_snippets = []\n            num_lines = len(lines)\n\n            for i, line in enumerate(lines, start=1):\n                if any(t in line for t in terms):\n                    start_idx = max(1, i - context_lines)\n                    end_idx = min(num_lines, i + context_lines)\n                    snippet = []\n                    for snippet_no in range(start_idx, end_idx + 1):\n                        text_content = lines[snippet_no - 1].rstrip(\"\\n\")\n                        snippet.append((snippet_no, text_content))\n                    file_snippets.append(snippet)\n\n            all_matches_per_file.append(file_snippets)\n\n        return all_matches_per_file\n\n    # ---------------------------------------------------------\n    # 3. MERGE OVERLAPPING/ADJACENT SNIPPETS\n    # ---------------------------------------------------------\n\n    def merge_file_snippets(file_snippets, gap=0):\n        \"\"\"\n        Merge overlapping or nearly adjacent snippets in a single file’s snippet list.\n        \"\"\"\n        intervals = []\n        for snippet in file_snippets:\n            if snippet:\n                start_line = snippet[0][0]\n                end_line = snippet[-1][0]\n                intervals.append((start_line, end_line, snippet))\n\n        intervals.sort(key=lambda x: x[0])  # sort by start line\n\n        merged = []\n        for start, end, snippet in intervals:\n            if not merged:\n                merged.append((start, end, snippet))\n                continue\n\n            prev_start, prev_end, prev_snippet = merged[-1]\n            if start <= prev_end + gap:\n                new_end = max(end, prev_end)\n                combined_dict = {}\n                for ln, txt in prev_snippet:\n                    combined_dict[ln] = txt\n                for ln, txt in snippet:\n                    combined_dict[ln] = txt\n                merged_snippet = [(ln, combined_dict[ln]) for ln in sorted(combined_dict)]\n                merged[-1] = (prev_start, new_end, merged_snippet)\n            else:\n                merged.append((start, end, snippet))\n\n        # Extract just the merged snippet portion\n        return [x[2] for x in merged]\n\n    def merge_all_snippets(all_files_snips, gap=0):\n        \"\"\"\n        Merge snippet blocks within each file.\n        all_files_snips is a list-of-lists:\n          [\n            [ snippetA, snippetB, ... ],  # file 1\n            [ snippetC, snippetD, ... ],  # file 2\n          ]\n        \"\"\"\n        merged = []\n        for snips in all_files_snips:\n            merged.append(merge_file_snippets(snips, gap=gap))\n        return merged\n\n    # ---------------------------------------------------------\n    # 4. RUN LOGIC: generate files, search, merge, and BUILD A STRING\n    # ---------------------------------------------------------\n\n    has_any_matches = False\n\n    # 1) Gather snippets around each match\n    context_snippets = find_lines_in_files_with_context(files_to_search, context_lines=context_lines)\n\n    # 2) Merge overlapping snippets\n    merged_snips = merge_all_snippets(context_snippets, gap=max_gap)\n\n    # 3) Build a string (instead of printing)\n    output = StringIO()\n\n    # Header\n    output.write(\"Sample files created successfully.\\n\\n\")\n    output.write(\"Search Results (by file, merging any overlapping context):\\n\\n\")\n\n    # For each file\n    for (filepath, snippet_list) in zip(files_to_search.keys(), merged_snips):\n        output.write(f\"FILE: {filepath[len(REPO_PATH) + 1:]}\\n\")\n        output.write(\"-\" * 60 + \"\\n\")\n        if not snippet_list:\n            output.write(\"  No matches found.\\n\")\n        else:\n            has_any_matches = True\n            for snippet_idx, snippet in enumerate(snippet_list, start=1):\n                snippet_start = snippet[0][0]\n                snippet_end = snippet[-1][0]\n                output.write(f\"Match #{snippet_idx}, lines {snippet_start} to {snippet_end}:\\n\")\n                for line_no, text in snippet:\n                    output.write(f\"  {line_no:3d} | {text}\\n\")\n                output.write(\"\\n\")\n        output.write(\"=\" * 60 + \"\\n\\n\")\n\n    file_content_string = output.getvalue()\n\n    if has_any_matches:\n        return file_content_string\n    return \"\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.884479Z","iopub.execute_input":"2025-02-10T23:20:47.884686Z","iopub.status.idle":"2025-02-10T23:20:47.90086Z","shell.execute_reply.started":"2025-02-10T23:20:47.884668Z","shell.execute_reply":"2025-02-10T23:20:47.900289Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def extract_patch_string(text):\n    pattern = r'<patch>(.*?)</patch>'\n    matches = re.findall(pattern, text, re.DOTALL)\n    if not matches:\n        return None\n    return \"\\n\".join(matches)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.901557Z","iopub.execute_input":"2025-02-10T23:20:47.901761Z","iopub.status.idle":"2025-02-10T23:20:47.915339Z","shell.execute_reply.started":"2025-02-10T23:20:47.901744Z","shell.execute_reply":"2025-02-10T23:20:47.914716Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"patching_prompt = \"\"\"\nYou will be implementing a git diff patch to solve an issue with the code repository.\nThis is the problem statement.\n\n{problem_statement}\n\nThese are the files that is thought to be relevant\n\n{file_content_string}\n\nWrite a git diff within <patch> and </patch> that fixes the problem.\n\nExample:\n\n<patch>\n--- a/first.txt\n+++ b/first.txt\n@@ -1,3 +1,3 @@\n start\n-first change\n+new first change\n middle\n@@ -7,4 +7,4 @@\n some content\n-second change\n+new second change\n more content\n--- a/second.txt\n+++ b/second.txt\n@@ -1,3 +1,3 @@\n beginning\n-old line\n+new line\n end\n</patch>\n\"\"\".strip()\n\nimport re\n\ndef get_patch_string(problem_statement, file_content_string):\n    \n    sampling_params = SamplingParams(\n        temperature=0.7,              # randomness of the sampling\n        min_p=0.01,\n        skip_special_tokens=True,     # Whether to skip special tokens in the output\n        max_tokens=MAX_MODEL_LEN,\n    )\n    \n    list_of_messages = [\n        [\n            {\n                \"role\": \"user\",\n                \"content\": patching_prompt.format(\n                    problem_statement=problem_statement,\n                    file_content_string=file_content_string,\n                )\n            },\n        ]\n    ]\n\n    list_of_texts = [\n        tokenizer.apply_chat_template(\n            conversation=messages,\n            tokenize=False,\n            add_generation_prompt=True\n        )\n        for messages in list_of_messages\n    ]\n    # print(list_of_texts)\n    print([len(tokenizer.encode(text)) for text in list_of_texts])\n    \n    request_output = llm.generate(prompts=list_of_texts, sampling_params=sampling_params)\n    if not request_output:\n        return \"\", \"\"\n    response_text = request_output[0].outputs[0].text\n    patch_string = extract_patch_string(response_text)\n    \n    return patch_string, response_text","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.915908Z","iopub.execute_input":"2025-02-10T23:20:47.916151Z","iopub.status.idle":"2025-02-10T23:20:47.929735Z","shell.execute_reply.started":"2025-02-10T23:20:47.916131Z","shell.execute_reply":"2025-02-10T23:20:47.929168Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"verifying_prompt = \"\"\"\nThis is the problem statement.\n\n{problem_statement}\n\nThese are the files that is thought to be relevant, which may not be complete.\n\n{file_content_string}\n\nThis is the proposed batch to fix the problem.\n\n{patch_string}\n\nFirstly, list your observations.\nThen, evaluate whether the patch fully fixes the problem described in the problem statement.\n\nEnd your response with exactly either of\n- <label>Yes</label>, this fixes the problem.\n- <label>No</label>, this does not fix the problem.\n\nNote\n- Only evaluate, do not provide suggestion on how to fix.\n- Remember to write exactly either of <label>Yes</label> or <label>No</label> in the last line\n\"\"\".strip()\n\n\ndef get_chosen_patch(problem_statement, file_content_string, patch_string):\n\n    sampling_params = SamplingParams(\n        temperature=0.7,              # randomness of the sampling\n        min_p=0.01,\n        skip_special_tokens=True,     # Whether to skip special tokens in the output\n        max_tokens=MAX_TOKENS,\n    )\n\n    list_of_messages = [\n        [\n            {\n                \"role\": \"user\",\n                \"content\": verifying_prompt.format(\n                    problem_statement=problem_statement,\n                    file_content_string=file_content_string,\n                    patch_string=patch_string,\n                )\n            },\n        ] for _ in range(MAX_NUM_SEQS)\n    ]\n\n    list_of_texts = [\n        tokenizer.apply_chat_template(\n            conversation=messages,\n            tokenize=False,\n            add_generation_prompt=True\n        )\n        for messages in list_of_messages\n    ]\n    # print(list_of_texts)\n    print(\"get_chosen_patch\", [len(tokenizer.encode(text)) for text in list_of_texts])\n    request_outputs = llm.generate(prompts=list_of_texts, sampling_params=sampling_params)\n    if not request_outputs:\n        return None, \"\"\n    response_texts = [request_output.outputs[0].text for request_output in request_outputs]\n    print(\"get_chosen_patch\", [len(tokenizer.encode(text)) for text in response_texts])\n\n    judgments = [\"<label>Yes</label>\" in response_text for response_text in response_texts]\n    print(judgments)\n    for response_text, judgment in zip(response_texts, judgments):\n        if judgment is True:\n            # return None, response_text  # NB: last response text\n            return patch_string, response_text\n\n    # return patch_string, response_text\n    return None, response_text  # NB: last response text","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.930364Z","iopub.execute_input":"2025-02-10T23:20:47.930568Z","iopub.status.idle":"2025-02-10T23:20:47.943746Z","shell.execute_reply.started":"2025-02-10T23:20:47.930551Z","shell.execute_reply":"2025-02-10T23:20:47.943175Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predict function","metadata":{}},{"cell_type":"code","source":"def predict_inner(problem_statement: str, directory: str) -> str:\n    directory_string = stringify_directory(directory)\n    file_query, get_file_query_response_text = get_file_query(directory_string, problem_statement)\n    file_queries, get_file_query_response_texts = [file_query], [get_file_query_response_text]\n    for file_query, get_file_query_response_text in zip(file_queries, get_file_query_response_texts):\n        print(get_file_query_response_text)\n        print(\"file_query from get_file_query_response_text\")\n        if not os.getenv('KAGGLE_IS_COMPETITION_RERUN'): print(file_query)\n\n    file_content_strings = [fetch_file_contents(file_query) for file_query in file_queries]\n    for file_content_string in file_content_strings:\n        print(file_content_string)\n    file_content_strings = [file_content_string for file_content_string in file_content_strings if file_content_string != \"\"]\n    if len(file_content_strings) == 0:\n        return None\n\n    patch_string, get_patch_string_response_text = get_patch_string(problem_statement, file_content_strings[0])\n    patch_string_to_return = None\n    for patch_string, get_patch_string_response_text in zip([patch_string], [get_patch_string_response_text]):\n        print(get_patch_string_response_text)\n        print(\"patch_string from get_patch_string_response_text\")\n        if not os.getenv('KAGGLE_IS_COMPETITION_RERUN'): print(patch_string)\n        if patch_string is not None:\n            patch_string_to_return = patch_string\n    \n    if not patch_string_to_return:\n        return None\n\n    # patch_string = patch_string_to_return\n    # patch_string, get_chosen_patch_response_text = get_chosen_patch(problem_statement, file_content_string, patch_string)\n    # print(get_chosen_patch_response_text)\n    # print(\"patch_string from get_chosen_patch_response_text\")\n    # print(patch_string)\n\n    return patch_string_to_return","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.944366Z","iopub.execute_input":"2025-02-10T23:20:47.944571Z","iopub.status.idle":"2025-02-10T23:20:47.957494Z","shell.execute_reply.started":"2025-02-10T23:20:47.944553Z","shell.execute_reply":"2025-02-10T23:20:47.956883Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import io\nfrom typing import Optional\n\nskip_prediction = False\n\n\ndef predict(problem_statement: str, repo_archive: io.BytesIO, pip_packages_archive: io.BytesIO, env_setup_cmds_templates: list[str]) -> str:\n    \"\"\" Replace this function with your inference code.\n    Args:\n        problem_statement: The text of the git issue.\n        repo_archive: A BytesIO buffer path with a .tar containing the codebase that must be patched. The gateway will make this directory available immediately before this function runs.\n    \"\"\"\n    global skip_prediction\n    if skip_prediction:\n        return None\n\n    with open('repo_archive.tar', 'wb') as f:\n        f.write(repo_archive.read())\n    repo_path = REPO_PATH\n    if os.path.exists(repo_path):\n        shutil.rmtree(repo_path)\n    shutil.unpack_archive('repo_archive.tar', extract_dir=repo_path)\n    os.remove('repo_archive.tar')\n\n    for _ in range(1):\n        patch_string = predict_inner(problem_statement=problem_statement, directory=repo_path)\n        if patch_string is not None:\n            break\n    shutil.rmtree(repo_path)\n\n    if patch_string is None:\n        return None\n\n    print(\"submitted patch_string\")\n    print(patch_string)\n \n    # if not os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    #     skip_prediction = True\n\n    return patch_string","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.958184Z","iopub.execute_input":"2025-02-10T23:20:47.958399Z","iopub.status.idle":"2025-02-10T23:20:47.971425Z","shell.execute_reply.started":"2025-02-10T23:20:47.958381Z","shell.execute_reply":"2025-02-10T23:20:47.970804Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Get predict data without server","metadata":{}},{"cell_type":"code","source":"!mkdir -p /kaggle/tmp/konwinski-prize-alt\n!unzip -q -o /kaggle/input/konwinski-prize/data.a_zip -d /kaggle/tmp/konwinski-prize-alt/ 2>/dev/null || true","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:47.972088Z","iopub.execute_input":"2025-02-10T23:20:47.972294Z","iopub.status.idle":"2025-02-10T23:20:53.631506Z","shell.execute_reply.started":"2025-02-10T23:20:47.972275Z","shell.execute_reply":"2025-02-10T23:20:53.630662Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\ndef get_problem(problem_index):\n    df = pd.read_parquet('/kaggle/tmp/konwinski-prize-alt/data/data.parquet')\n    \n    problem_statement = df[\"problem_statement\"][problem_index]\n    repo_path = f\"/kaggle/tmp/konwinski-prize-alt/data/repos/repo__{df['instance_id'][problem_index]}\"\n    \n    import shutil\n    import tempfile\n    \n    with tempfile.TemporaryDirectory() as tmpdir:\n        shutil.make_archive(os.path.join(tmpdir, 'a_repo'), 'tar', repo_path)\n        with open(os.path.join(tmpdir, 'a_repo.tar'), 'rb') as f:\n            repo_archive = io.BytesIO(f.read())\n\n    return problem_statement, repo_path, repo_archive","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:53.632449Z","iopub.execute_input":"2025-02-10T23:20:53.632696Z","iopub.status.idle":"2025-02-10T23:20:53.637214Z","shell.execute_reply.started":"2025-02-10T23:20:53.632673Z","shell.execute_reply":"2025-02-10T23:20:53.636587Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"demo_problem_index = 0\n\nif not os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    problem_statement, repo_path, repo_archive = get_problem(problem_index=demo_problem_index)\n    \n    print(repo_path)\n    print(problem_statement)\n    print(len(list(repo_archive)))\n    print(len(list(repo_archive)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:53.637865Z","iopub.execute_input":"2025-02-10T23:20:53.638112Z","iopub.status.idle":"2025-02-10T23:20:53.796076Z","shell.execute_reply.started":"2025-02-10T23:20:53.638091Z","shell.execute_reply":"2025-02-10T23:20:53.795464Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if not os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    skip_prediction = False\n    problem_statement, repo_path, repo_archive = get_problem(problem_index=demo_problem_index)\n    patch_string = predict(problem_statement, repo_archive, None, None)","metadata":{"trusted":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-02-10T23:20:53.796845Z","iopub.execute_input":"2025-02-10T23:20:53.797198Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if not os.getenv('KAGGLE_IS_COMPETITION_RERUN') and patch_string is not None:\n    import polars as pl\n    df = pl.read_parquet('/kaggle/tmp/konwinski-prize-alt/data/data.parquet')\n    \n    import kaggle_evaluation.konwinski_prize_gateway\n    k_prize_gateway = kaggle_evaluation.konwinski_prize_gateway.KPrizeGateway()\n    k_prize_gateway.unpack_data_paths()\n\n    results = k_prize_gateway._evaluate_instance(\n        instance = df.row(demo_problem_index, named=True),\n        patch = patch_string,\n    )\n    from collections import Counter\n    print(demo_problem_index, Counter(result.unit_test_outcome for result in results[1:]))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if not os.getenv('KAGGLE_IS_COMPETITION_RERUN') and patch_string is not None:\n    from kaggle_evaluation.konwinski_prize_gateway import UnitTestOutcome\n    for result in results[1:]:\n        if result.unit_test_outcome != UnitTestOutcome.PASSED:\n            print(result.test_name)\n            print(result.fail_description)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"When your notebook is run on the hidden test set, inference_server.serve must be called within 15 minutes of the notebook starting or the gateway will throw an error. If you need more than 15 minutes to load your model you can do so during the very first predict call, which does not have the usual 30 minute response deadline.","metadata":{"papermill":{"duration":0.001889,"end_time":"2024-12-11T03:22:08.856283","exception":false,"start_time":"2024-12-11T03:22:08.854394","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"# Evaluation with inference server","metadata":{}},{"cell_type":"code","source":"skip_prediction = False","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inference_server = kaggle_evaluation.konwinski_prize_inference_server.KPrizeInferenceServer(\n    get_number_of_instances,   \n    predict\n)\n\nif os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    inference_server.serve()\nelse:\n    inference_server.run_local_gateway(\n        data_paths=(\n            '/kaggle/input/konwinski-prize/',  # Path to the entire competition dataset\n            '/kaggle/tmp/konwinski-prize/',   # Path to a scratch directory for unpacking data.a_zip.\n        )\n    )","metadata":{"trusted":true,"_kg_hide-output":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}