|
| 1 | +"""Template-based code generator implementation""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +from graph_net.agent.metadata_analyzer.model_metadata import ModelMetadata |
| 7 | +from graph_net.agent.code_generator.base import BaseCodeGenerator |
| 8 | +from graph_net.agent.utils.exceptions import CodeGenError |
| 9 | + |
| 10 | +# Constants for safe vocab size calculation |
| 11 | +DEFAULT_VOCAB_SIZE = 30522 |
| 12 | +MIN_SAFE_VOCAB_SIZE = 100 |
| 13 | +FIXED_SAFE_LIMIT = 25000 # For very large vocabularies or specific model types |
| 14 | +LARGE_VOCAB_THRESHOLD = 100000 |
| 15 | +MEDIUM_VOCAB_THRESHOLD = 50000 |
| 16 | +SMALL_VOCAB_THRESHOLD = 10000 |
| 17 | +LARGE_VOCAB_RATIO = 0.7 |
| 18 | +MEDIUM_VOCAB_RATIO = 0.8 |
| 19 | +SMALL_VOCAB_RATIO = 0.9 |
| 20 | + |
| 21 | + |
| 22 | +class TemplateCodeGenerator(BaseCodeGenerator): |
| 23 | + """Code generator using Jinja2 template""" |
| 24 | + |
| 25 | + def __init__(self, template_path: Optional[str] = None): |
| 26 | + """ |
| 27 | + Args: |
| 28 | + template_path: Path to Jinja2 template file (optional) |
| 29 | + """ |
| 30 | + self.template_path = template_path |
| 31 | + self._template = None |
| 32 | + |
| 33 | + def generate( |
| 34 | + self, |
| 35 | + model_dir: Path, |
| 36 | + model_metadata: ModelMetadata, |
| 37 | + output_dir: Path, |
| 38 | + ) -> Path: |
| 39 | + """ |
| 40 | + Generate run_model.py extraction script using template |
| 41 | + |
| 42 | + Args: |
| 43 | + model_dir: Path to model directory |
| 44 | + model_metadata: Model metadata extracted from configuration |
| 45 | + output_dir: Output directory for generated script |
| 46 | + |
| 47 | + Returns: |
| 48 | + Path to generated script file |
| 49 | + """ |
| 50 | + try: |
| 51 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 52 | + code = self._generate_code(model_dir, model_metadata) |
| 53 | + |
| 54 | + script_path = output_dir / "run_model.py" |
| 55 | + with open(script_path, 'w', encoding='utf-8') as f: |
| 56 | + f.write(code) |
| 57 | + |
| 58 | + return script_path |
| 59 | + except Exception as e: |
| 60 | + raise CodeGenError(f"Failed to generate code: {e}") from e |
| 61 | + |
| 62 | + def _generate_code(self, model_dir: Path, model_metadata: ModelMetadata) -> str: |
| 63 | + """Generate complete extraction script code string""" |
| 64 | + # Generate model loading code |
| 65 | + load_code = self._generate_model_loader(model_dir, model_metadata) |
| 66 | + |
| 67 | + # Generate input construction code |
| 68 | + input_code = self._generate_input_code(model_metadata) |
| 69 | + |
| 70 | + # Generate main code |
| 71 | + code = f'''import torch |
| 72 | +try: |
| 73 | + from transformers import AutoModel |
| 74 | +except ImportError: |
| 75 | + raise ImportError("transformers is required. Install with: pip install transformers") |
| 76 | +
|
| 77 | +import graph_net |
| 78 | +
|
| 79 | +def main(): |
| 80 | + # Load model |
| 81 | +{self._indent(load_code, 4)} |
| 82 | + |
| 83 | + # Prepare inputs |
| 84 | +{self._indent(input_code, 4)} |
| 85 | + |
| 86 | + # Extract graph |
| 87 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 88 | + model = model.to(device).eval() |
| 89 | + |
| 90 | + # Move inputs to same device as model |
| 91 | + inputs = {{k: v.to(device) for k, v in inputs.items()}} |
| 92 | + |
| 93 | + wrapped = graph_net.torch.extract(name="{model_metadata.model_id}", dynamic=True)(model).eval() |
| 94 | + |
| 95 | + with torch.no_grad(): |
| 96 | + wrapped(**inputs) |
| 97 | +
|
| 98 | +if __name__ == "__main__": |
| 99 | + main() |
| 100 | +''' |
| 101 | + return code |
| 102 | + |
| 103 | + def _generate_model_loader(self, model_dir: Path, model_metadata: ModelMetadata) -> str: |
| 104 | + """Generate model loading code based on model type""" |
| 105 | + model_path = str(model_dir).replace("\\", "/") |
| 106 | + |
| 107 | + if model_metadata.model_type in ['bert', 'gpt', 't5', 'roberta']: |
| 108 | + return f'model = AutoModel.from_pretrained("{model_path}")' |
| 109 | + elif model_metadata.model_type in ['resnet', 'vgg', 'densenet']: |
| 110 | + return f'model = torchvision.models.{model_metadata.model_type}(pretrained=True)' |
| 111 | + else: |
| 112 | + # Generic loading |
| 113 | + return f'model = AutoModel.from_pretrained("{model_path}")' |
| 114 | + |
| 115 | + def _generate_input_code(self, model_metadata: ModelMetadata) -> str: |
| 116 | + """Generate input tensor construction code based on model metadata""" |
| 117 | + lines = ['inputs = {}'] |
| 118 | + |
| 119 | + for name, shape in model_metadata.input_shapes.items(): |
| 120 | + dtype = model_metadata.input_dtypes.get(name, "int64") |
| 121 | + torch_dtype = self._get_torch_dtype(dtype) |
| 122 | + shape_tuple = f"({', '.join(map(str, shape))})" |
| 123 | + |
| 124 | + if dtype == "int64": |
| 125 | + if "input_ids" in name.lower(): |
| 126 | + safe_vocab_size = self._calculate_safe_vocab_size(model_metadata) |
| 127 | + lines.append(f'inputs["{name}"] = torch.randint(0, {safe_vocab_size}, {shape_tuple}, dtype={torch_dtype})') |
| 128 | + else: |
| 129 | + lines.append(f'inputs["{name}"] = torch.ones({shape_tuple}, dtype={torch_dtype})') |
| 130 | + else: |
| 131 | + lines.append(f'inputs["{name}"] = torch.randn({shape_tuple}, dtype={torch_dtype})') |
| 132 | + |
| 133 | + return "\n".join(lines) |
| 134 | + |
| 135 | + def _get_torch_dtype(self, dtype: str) -> str: |
| 136 | + """Convert dtype string to torch dtype""" |
| 137 | + if dtype == "int64": |
| 138 | + return "torch.int64" |
| 139 | + elif dtype == "float32": |
| 140 | + return "torch.float32" |
| 141 | + else: |
| 142 | + return f"torch.{dtype}" |
| 143 | + |
| 144 | + def _calculate_safe_vocab_size(self, model_metadata: ModelMetadata) -> int: |
| 145 | + """Calculate safe vocabulary size for input generation""" |
| 146 | + if model_metadata.embedding_size: |
| 147 | + return max(MIN_SAFE_VOCAB_SIZE, model_metadata.embedding_size - 1) |
| 148 | + |
| 149 | + vocab_size = model_metadata.vocab_size or DEFAULT_VOCAB_SIZE |
| 150 | + model_type = (model_metadata.model_type or "").lower() |
| 151 | + |
| 152 | + # Model-type-specific limits |
| 153 | + if self._is_large_vocab_model_type(model_type): |
| 154 | + return FIXED_SAFE_LIMIT |
| 155 | + |
| 156 | + # Size-based strategy |
| 157 | + if vocab_size > LARGE_VOCAB_THRESHOLD: |
| 158 | + return FIXED_SAFE_LIMIT |
| 159 | + elif vocab_size > MEDIUM_VOCAB_THRESHOLD: |
| 160 | + return max(MIN_SAFE_VOCAB_SIZE, int(vocab_size * LARGE_VOCAB_RATIO)) |
| 161 | + elif vocab_size > SMALL_VOCAB_THRESHOLD: |
| 162 | + return max(MIN_SAFE_VOCAB_SIZE, int(vocab_size * MEDIUM_VOCAB_RATIO)) |
| 163 | + else: |
| 164 | + return max(MIN_SAFE_VOCAB_SIZE, int(vocab_size * SMALL_VOCAB_RATIO)) |
| 165 | + |
| 166 | + def _is_large_vocab_model_type(self, model_type: str) -> bool: |
| 167 | + """Check if model type typically has large vocabulary but small embedding""" |
| 168 | + return "xlm-roberta" in model_type or "xlm_roberta" in model_type or "roberta" in model_type |
| 169 | + |
| 170 | + def _indent(self, text: str, spaces: int) -> str: |
| 171 | + """Indent text by specified spaces""" |
| 172 | + indent = " " * spaces |
| 173 | + return "\n".join(indent + line for line in text.split("\n")) |
0 commit comments