|
| 1 | +import os |
| 2 | +import logging |
| 3 | +from typing import Dict, Any |
| 4 | + |
| 5 | +class TemplateCoder: |
| 6 | + def __init__(self): |
| 7 | + self.logger = logging.getLogger("TemplateCoder") |
| 8 | + |
| 9 | + def generate(self, model_dir: str, meta_info: Dict[str, Any]) -> str: |
| 10 | + """ |
| 11 | + Generate a python script to load the model and run extraction. |
| 12 | + """ |
| 13 | + script_content = self._create_script_content(model_dir, meta_info) |
| 14 | + |
| 15 | + output_path = os.path.join(model_dir, "run_extraction.py") |
| 16 | + with open(output_path, "w", encoding="utf-8") as f: |
| 17 | + f.write(script_content) |
| 18 | + |
| 19 | + return output_path |
| 20 | + |
| 21 | + def _create_script_content(self, model_dir: str, meta_info: Dict[str, Any]) -> str: |
| 22 | + # Basic template for HF models |
| 23 | + input_names = meta_info.get("input_names", ["input_ids"]) |
| 24 | + input_shape = meta_info.get("input_shape", [1, 128]) |
| 25 | + input_dtype = meta_info.get("input_dtype", "int64") |
| 26 | + |
| 27 | + # Construct input generation code |
| 28 | + input_gen_code = "" |
| 29 | + if meta_info["task_type"] == "nlp": |
| 30 | + input_gen_code += f""" |
| 31 | + # NLP Inputs |
| 32 | + input_ids = torch.randint(0, 100, {tuple(input_shape)}, dtype=torch.int64) |
| 33 | + attention_mask = torch.ones({tuple(input_shape)}, dtype=torch.int64) |
| 34 | + inputs = (input_ids, attention_mask) |
| 35 | + """ |
| 36 | + elif meta_info["task_type"] == "cv": |
| 37 | + input_gen_code += f""" |
| 38 | + # CV Inputs |
| 39 | + inputs = (torch.randn({tuple(input_shape)}, dtype=torch.float32),) |
| 40 | + """ |
| 41 | + |
| 42 | + template = f""" |
| 43 | +import sys |
| 44 | +import os |
| 45 | +import torch |
| 46 | +from transformers import AutoModel, AutoConfig |
| 47 | +
|
| 48 | +# Ensure graph_net is in path |
| 49 | +sys.path.append(os.getcwd()) |
| 50 | +
|
| 51 | +def main(): |
| 52 | + model_path = r"{model_dir}" |
| 53 | + output_dir = r"{model_dir}/extracted_sample" |
| 54 | + |
| 55 | + print(f"Loading model from {{model_path}}...") |
| 56 | + try: |
| 57 | + model = AutoModel.from_pretrained(model_path, trust_remote_code=True) |
| 58 | + model.eval() |
| 59 | + except Exception as e: |
| 60 | + print(f"Failed to load model: {{e}}") |
| 61 | + sys.exit(1) |
| 62 | +
|
| 63 | + print("Generating inputs...") |
| 64 | + {input_gen_code} |
| 65 | + |
| 66 | + # Move to CUDA if available |
| 67 | + device = "cuda" if torch.cuda.is_available() else "cpu" |
| 68 | + model.to(device) |
| 69 | + inputs = tuple(t.to(device) for t in inputs) |
| 70 | +
|
| 71 | + print("Starting extraction...") |
| 72 | + # Setup environment variable for GraphNet workspace |
| 73 | + os.environ['GRAPH_NET_EXTRACT_WORKSPACE'] = output_dir |
| 74 | + |
| 75 | + # Use the extract API from graph_net |
| 76 | + # extract(name, dynamic=True)(model) returns a compiled model |
| 77 | + # We need to run it once to trigger compilation and extraction |
| 78 | + from graph_net.torch.extractor import extract |
| 79 | + |
| 80 | + compiled_model = extract(name="subgraph", dynamic=True)(model) |
| 81 | + |
| 82 | + print("Running forward pass to trigger extraction...") |
| 83 | + with torch.no_grad(): |
| 84 | + if isinstance(inputs, tuple): |
| 85 | + compiled_model(*inputs) |
| 86 | + elif isinstance(inputs, dict): |
| 87 | + compiled_model(**inputs) |
| 88 | + else: |
| 89 | + compiled_model(inputs) |
| 90 | + |
| 91 | + print(f"Extraction complete. Results in {{output_dir}}") |
| 92 | +
|
| 93 | +if __name__ == "__main__": |
| 94 | + main() |
| 95 | +""" |
| 96 | + return template |
0 commit comments