|
7 | 7 | import re |
8 | 8 | from textwrap import indent |
9 | 9 |
|
| 10 | +from jinja2 import Environment, FileSystemLoader, StrictUndefined |
| 11 | + |
10 | 12 | from transformer_nuggets.export_autograd_triton.clean_triton import clean_triton_module |
11 | 13 | from transformer_nuggets.export_autograd_triton.specs import CapturedSpecialization |
12 | 14 |
|
13 | 15 |
|
| 16 | +_TEMPLATE_ENV = Environment( |
| 17 | + loader=FileSystemLoader(Path(__file__).with_name("templates")), |
| 18 | + undefined=StrictUndefined, |
| 19 | + keep_trailing_newline=True, |
| 20 | +) |
| 21 | + |
| 22 | + |
14 | 23 | def generate_autograd_source( |
15 | 24 | fn: Callable[..., object], |
16 | 25 | exported_name: str, |
17 | 26 | specializations: list[CapturedSpecialization], |
18 | 27 | ) -> str: |
19 | 28 | signature = inspect.signature(fn) |
20 | | - wrapper = _generate_public_wrapper(exported_name, signature) |
21 | | - specs_literal = pprint.pformat( |
22 | | - [_spec_to_metadata(index, spec) for index, spec in enumerate(specializations)], |
23 | | - width=100, |
24 | | - sort_dicts=False, |
| 29 | + return _TEMPLATE_ENV.get_template("autograd_module.py.j2").render( |
| 30 | + specs_literal=pprint.pformat( |
| 31 | + [_spec_to_metadata(index, spec) for index, spec in enumerate(specializations)], |
| 32 | + width=100, |
| 33 | + sort_dicts=False, |
| 34 | + ), |
| 35 | + wrapper=_generate_public_wrapper(exported_name, signature).rstrip(), |
25 | 36 | ) |
26 | | - return f"""from __future__ import annotations |
27 | | -
|
28 | | -import importlib.util |
29 | | -from pathlib import Path |
30 | | -
|
31 | | -import torch |
32 | | -
|
33 | | -_ARTIFACTS_DIR = Path(__file__).with_name(f"{{Path(__file__).stem}}_artifacts") |
34 | | -
|
35 | | -_SPECS = {specs_literal} |
36 | | -
|
37 | | -
|
38 | | -def _load_runner(module_filename): |
39 | | - if module_filename is None: |
40 | | - return None |
41 | | - module_path = _ARTIFACTS_DIR / module_filename |
42 | | - spec = importlib.util.spec_from_file_location(module_path.stem, module_path) |
43 | | - module = importlib.util.module_from_spec(spec) |
44 | | - if spec.loader is None: |
45 | | - raise RuntimeError(f"Could not load compiled source module {{module_path}}") |
46 | | - spec.loader.exec_module(module) |
47 | | - return module.call |
48 | | -
|
49 | | -
|
50 | | -_FORWARD_RUNNERS = [_load_runner(spec["forward_module"]) for spec in _SPECS] |
51 | | -_BACKWARD_RUNNERS = [_load_runner(spec["backward_module"]) for spec in _SPECS] |
52 | | -
|
53 | | -
|
54 | | -class _CompiledAutogradFunction(torch.autograd.Function): |
55 | | - @staticmethod |
56 | | - def forward(ctx, spec_id, *runtime_tensors): |
57 | | - spec = _SPECS[spec_id] |
58 | | - outputs = _FORWARD_RUNNERS[spec_id](list(runtime_tensors)) |
59 | | - if not isinstance(outputs, tuple): |
60 | | - outputs = tuple(outputs) |
61 | | - user_outputs = outputs[: spec["num_user_outputs"]] |
62 | | - residuals = outputs[spec["num_user_outputs"] :] |
63 | | - named_residuals = tuple(zip(spec["forward_residual_names"], residuals, strict=True)) |
64 | | - ctx.spec_id = spec_id |
65 | | - ctx.runtime_tensor_count = len(runtime_tensors) |
66 | | - ctx.saved_tensor_residual_names = tuple( |
67 | | - name for name, residual in named_residuals if isinstance(residual, torch.Tensor) |
68 | | - ) |
69 | | - ctx.saved_non_tensor_residuals = {{ |
70 | | - name: residual for name, residual in named_residuals if not isinstance(residual, torch.Tensor) |
71 | | - }} |
72 | | - ctx.save_for_backward( |
73 | | - *(residual for _, residual in named_residuals if isinstance(residual, torch.Tensor)) |
74 | | - ) |
75 | | - non_differentiable_outputs = tuple( |
76 | | - output |
77 | | - for output, is_differentiable in zip( |
78 | | - user_outputs, |
79 | | - spec["differentiable_output_mask"], |
80 | | - strict=True, |
81 | | - ) |
82 | | - if isinstance(output, torch.Tensor) and not is_differentiable |
83 | | - ) |
84 | | - if non_differentiable_outputs: |
85 | | - ctx.mark_non_differentiable(*non_differentiable_outputs) |
86 | | - if spec["output_kind"] == "single": |
87 | | - return user_outputs[0] |
88 | | - return tuple(user_outputs) |
89 | | -
|
90 | | - @staticmethod |
91 | | - def backward(ctx, *grad_outputs): |
92 | | - spec = _SPECS[ctx.spec_id] |
93 | | - grad_outputs = tuple( |
94 | | - grad_output.contiguous() if isinstance(grad_output, torch.Tensor) else grad_output |
95 | | - for index, grad_output in enumerate(grad_outputs) |
96 | | - if spec["differentiable_output_mask"][index] |
97 | | - ) |
98 | | - backward_runner = _BACKWARD_RUNNERS[ctx.spec_id] |
99 | | - if backward_runner is None: |
100 | | - raise RuntimeError("Selected export_autograd_triton specialization has no backward graph") |
101 | | - saved_residuals = dict(ctx.saved_non_tensor_residuals) |
102 | | - saved_residuals.update(zip(ctx.saved_tensor_residual_names, ctx.saved_tensors, strict=True)) |
103 | | - backward_saved_inputs = tuple( |
104 | | - saved_residuals[name] for name in spec["backward_saved_input_names"] |
105 | | - ) |
106 | | - grads = backward_runner(list(backward_saved_inputs + grad_outputs)) |
107 | | - if not isinstance(grads, tuple): |
108 | | - grads = tuple(grads) |
109 | | - if len(grads) < ctx.runtime_tensor_count: |
110 | | - grads = grads + (None,) * (ctx.runtime_tensor_count - len(grads)) |
111 | | - if len(grads) > ctx.runtime_tensor_count: |
112 | | - grads = grads[: ctx.runtime_tensor_count] |
113 | | - return (None, *grads) |
114 | | -
|
115 | | -
|
116 | | -def _run_with_bound_args(bound_args): |
117 | | - spec_id = _select_spec(bound_args) |
118 | | - spec = _SPECS[spec_id] |
119 | | - runtime_tensors = tuple(bound_args[name] for name in spec["runtime_tensor_names"]) |
120 | | - if spec["needs_autograd"]: |
121 | | - result = _CompiledAutogradFunction.apply(spec_id, *runtime_tensors) |
122 | | - if spec["output_kind"] == "list": |
123 | | - return list(result) |
124 | | - return result |
125 | | - return _run_forward_only(spec_id, runtime_tensors) |
126 | | -
|
127 | | -
|
128 | | -def _run_forward_only(spec_id, runtime_tensors): |
129 | | - spec = _SPECS[spec_id] |
130 | | - outputs = _FORWARD_RUNNERS[spec_id](list(runtime_tensors)) |
131 | | - if not isinstance(outputs, tuple): |
132 | | - outputs = tuple(outputs) |
133 | | - user_outputs = outputs[: spec["num_user_outputs"]] |
134 | | - if spec["output_kind"] == "single": |
135 | | - return user_outputs[0] |
136 | | - if spec["output_kind"] == "list": |
137 | | - return list(user_outputs) |
138 | | - return tuple(user_outputs) |
139 | | -
|
140 | | -
|
141 | | -def _select_spec(bound_args): |
142 | | - matches = [] |
143 | | - failures = [] |
144 | | - for spec_id, spec in enumerate(_SPECS): |
145 | | - reasons = _mismatch_reasons(spec, bound_args) |
146 | | - if reasons: |
147 | | - failures.append((spec, reasons)) |
148 | | - else: |
149 | | - matches.append(spec_id) |
150 | | - if len(matches) == 1: |
151 | | - return matches[0] |
152 | | - if len(matches) > 1: |
153 | | - names = ", ".join(_SPECS[spec_id]["name"] for spec_id in matches) |
154 | | - raise RuntimeError(f"Ambiguous export_autograd_triton specializations matched: {{names}}") |
155 | | - raise RuntimeError(_format_no_match(bound_args, failures)) |
156 | | -
|
157 | | -
|
158 | | -def _mismatch_reasons(spec, bound_args): |
159 | | - reasons = [] |
160 | | - symbols = {{}} |
161 | | - for name, expected in spec["static_args"].items(): |
162 | | - actual = bound_args.get(name) |
163 | | - if actual != expected: |
164 | | - reasons.append(f"static {{name}}={{actual!r}} != {{expected!r}}") |
165 | | - for guard in spec["tensor_guards"]: |
166 | | - tensor = bound_args.get(guard["name"]) |
167 | | - reason = _tensor_mismatch_reason(tensor, guard, symbols) |
168 | | - if reason is not None: |
169 | | - reasons.append(reason) |
170 | | - return reasons |
171 | | -
|
172 | | -
|
173 | | -def _tensor_mismatch_reason(tensor, guard, symbols): |
174 | | - name = guard["name"] |
175 | | - if not isinstance(tensor, torch.Tensor): |
176 | | - return f"{{name}} is {{type(tensor).__name__}}, expected Tensor" |
177 | | - expected_dtype = getattr(torch, guard["dtype"]) |
178 | | - if tensor.dtype is not expected_dtype: |
179 | | - return f"{{name}} dtype {{tensor.dtype}} != torch.{{guard['dtype']}}" |
180 | | - if tensor.device.type != guard["device_type"]: |
181 | | - return f"{{name}} device type {{tensor.device.type}} != {{guard['device_type']}}" |
182 | | - if tensor.device.index != guard["device_index"]: |
183 | | - return f"{{name}} device index {{tensor.device.index}} != {{guard['device_index']}}" |
184 | | - if tensor.dim() != guard["rank"]: |
185 | | - return f"{{name}} rank {{tensor.dim()}} != {{guard['rank']}}" |
186 | | - shape_reason = _shape_mismatch_reason(name, tensor, guard, symbols) |
187 | | - if shape_reason is not None: |
188 | | - return shape_reason |
189 | | - if tuple(tensor.stride()) != tuple(guard["stride"]): |
190 | | - return f"{{name}} stride {{tuple(tensor.stride())}} != {{tuple(guard['stride'])}}" |
191 | | - return None |
192 | | -
|
193 | | -
|
194 | | -def _shape_mismatch_reason(name, tensor, guard, symbols): |
195 | | - for dim, expected in enumerate(guard["shape"]): |
196 | | - actual = int(tensor.shape[dim]) |
197 | | - if isinstance(expected, dict): |
198 | | - symbol = expected["symbol"] |
199 | | - if expected["min"] is not None and actual < expected["min"]: |
200 | | - return f"{{name}} shape dim {{dim}}={{actual}} is less than {{symbol}} min {{expected['min']}}" |
201 | | - if expected["max"] is not None and actual > expected["max"]: |
202 | | - return f"{{name}} shape dim {{dim}}={{actual}} is greater than {{symbol}} max {{expected['max']}}" |
203 | | - if symbol in symbols and symbols[symbol] != actual: |
204 | | - return f"{{name}} shape dim {{dim}}={{actual}} does not equal {{symbol}}={{symbols[symbol]}}" |
205 | | - symbols[symbol] = actual |
206 | | - elif actual != expected: |
207 | | - return f"{{name}} shape dim {{dim}}={{actual}} != {{expected}}" |
208 | | - return None |
209 | | -
|
210 | | -
|
211 | | -def _format_no_match(bound_args, failures): |
212 | | - lines = ["No export_autograd_triton specialization matched the runtime inputs.", "Received:"] |
213 | | - for name, value in bound_args.items(): |
214 | | - if isinstance(value, torch.Tensor): |
215 | | - lines.append( |
216 | | - f" {{name}}: dtype={{value.dtype}}, device={{value.device}}, " |
217 | | - f"shape={{tuple(value.shape)}}, stride={{tuple(value.stride())}}" |
218 | | - ) |
219 | | - else: |
220 | | - lines.append(f" {{name}}: {{value!r}}") |
221 | | - lines.append("Expected specializations:") |
222 | | - for spec, reasons in failures: |
223 | | - lines.append(f" - {{spec['name']}}:") |
224 | | - for reason in reasons: |
225 | | - lines.append(f" {{reason}}") |
226 | | - return "\\n".join(lines) |
227 | | -
|
228 | | -
|
229 | | -{wrapper} |
230 | | -""" |
231 | 37 |
|
232 | 38 |
|
233 | 39 | def write_autograd_source( |
|
0 commit comments