"""Generate a proposed Python repair. Never execute the returned code.""" from pathlib import Path import argparse import os import re import sys BASE_MODEL = "Qwen/Qwen2.5-Coder-1.5B-Instruct" BASE_REVISION = "2e1fd397ee46e1388853d2af2c993145b0f1098a" def extract_code(answer): blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", answer, re.S) return blocks[-1].strip() if blocks else answer.strip() def build_prompt(code, requirements): return ( "Repair the Python function below. Preserve its function name, signature, " "and every stated requirement. Return only the complete corrected Python " "code in a Python code block.\n\nRequirements:\n" + requirements + "\n\nBuggy Python code:\n```python\n" + code + "\n```" ) def load_model(adapter, device, offline=False): if os.environ.get("PYTORCH_ENABLE_MPS_FALLBACK") == "1": raise RuntimeError("Unset PYTORCH_ENABLE_MPS_FALLBACK before loading.") import torch from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel if device == "mps" and not torch.backends.mps.is_available(): raise RuntimeError("MPS unavailable; select --device cpu explicitly.") dtype = torch.bfloat16 if device == "mps" else torch.float32 tokenizer = AutoTokenizer.from_pretrained( str(adapter), local_files_only=True, trust_remote_code=False ) model = AutoModelForCausalLM.from_pretrained( BASE_MODEL, revision=BASE_REVISION, local_files_only=offline, trust_remote_code=False, torch_dtype=dtype, attn_implementation="eager", ) model = PeftModel.from_pretrained(model, str(adapter), is_trainable=False) return model.to(device).eval(), tokenizer def propose_repair(model, tokenizer, code, requirements, *, device, max_new_tokens=384): import torch if not 1 <= max_new_tokens <= 384: raise ValueError("max_new_tokens must be between 1 and 384") messages = [{"role": "user", "content": build_prompt(code, requirements)}] inputs = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_tensors="pt" ) if inputs.shape[-1] > 3072: raise ValueError("Prompt exceeds 3072 tokens; shorten it. No silent truncation.") inputs = inputs.to(device) torch.manual_seed(42) if device == "mps": torch.mps.manual_seed(42) # Build a fresh greedy configuration rather than inheriting sampling defaults. from transformers import GenerationConfig config = GenerationConfig( do_sample=False, num_beams=1, max_new_tokens=max_new_tokens, eos_token_id=model.generation_config.eos_token_id, pad_token_id=(tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id), use_cache=True, ) with torch.inference_mode(): output = model.generate( input_ids=inputs, attention_mask=torch.ones_like(inputs), generation_config=config, ) answer = tokenizer.decode(output[0, inputs.shape[-1]:], skip_special_tokens=True) return extract_code(answer) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--code", type=Path, help="Buggy Python file; omit to read stdin") parser.add_argument("--requirements", required=True, help="Expected behavior and constraints") parser.add_argument("--adapter", type=Path, default=Path(__file__).resolve().parent) parser.add_argument("--device", choices=["cpu", "mps"], default="cpu") parser.add_argument("--offline", action="store_true", help="Require cached base weights") parser.add_argument("--max-new-tokens", type=int, default=384) args = parser.parse_args() if not 1 <= args.max_new_tokens <= 384: parser.error("--max-new-tokens must be between 1 and 384") if args.code: with args.code.open("r", encoding="utf-8") as source: code = source.read(1_048_577) else: code = sys.stdin.read(1_048_577) if not code.strip() or len(code) > 1_048_576: parser.error("Code must be nonempty and at most 1048576 characters") if not args.requirements.strip() or len(args.requirements) > 65_536: parser.error("Requirements must be nonempty and at most 65536 characters") model, tokenizer = load_model(args.adapter, args.device, args.offline) print(propose_repair(model, tokenizer, code, args.requirements, device=args.device, max_new_tokens=args.max_new_tokens)) if __name__ == "__main__": main()