Download neuro_compiler/api.py from chrisuser/NeuroCC_0.4.0: direct link, hf CLI and curl.
- Browser
- Download file 5.59 kB
-
https://huggingface.co/chrisuser/NeuroCC_0.4.0/resolve/main/neuro_compiler/api.py
- Command line
-
hf download hf://chrisuser/NeuroCC_0.4.0/neuro_compiler/api.py
-
curl -L -o api.py https://huggingface.co/chrisuser/NeuroCC_0.4.0/resolve/main/neuro_compiler/api.py
5.59 kB
| """Portable NeuroCC 0.4.0 API. | |
| D5A is the default and preserves the qualified source-to-function behavior. | |
| D5-Final is available only as an explicitly selected experimental backend. | |
| Generated bytes are returned as data; this package never executes them. | |
| """ | |
| from dataclasses import dataclass | |
| import importlib | |
| import json | |
| from pathlib import Path | |
| import sys | |
| from typing import Sequence | |
| import torch | |
| PACKAGE_ROOT = Path(__file__).resolve().parent | |
| RUNTIME_ROOT = PACKAGE_ROOT / 'runtime' | |
| def _activate_runtime(): | |
| value = str(RUNTIME_ROOT) | |
| if value not in sys.path: | |
| sys.path.insert(0, value) | |
| class CompilationResult: | |
| valid: bool | |
| code: bytes | |
| size: int | |
| record: dict | |
| class NeuroCompiler: | |
| """Load one frozen NeuroCC implementation and compile isolated sources. | |
| Parameters | |
| ---------- | |
| device: | |
| ``"auto"`` selects CUDA when available, otherwise CPU. | |
| implementation: | |
| ``"d5a"`` (default) or ``"d5-final"``. The latter is experimental. | |
| compact: | |
| Preserve the qualified compact liveness/allocation configuration. | |
| use_ssa_memory: | |
| Enable the shipped exact-SSA development-memory optimization. Matching | |
| source/SSA/ABI lanes use the frozen packet; misses use ordinary D5A. | |
| hyperopt: | |
| Enable the optional frozen H7 hyperoptimizer. It proposes guarded | |
| alternatives before the selected existing backend; rejected or | |
| unsupported candidates fall back to ordinary compilation. | |
| """ | |
| def __init__(self, device='auto', implementation='d5a', *, compact=True, | |
| encoder_chunk=2048, span_chunk=16, use_ssa_memory=True, | |
| hyperopt=False): | |
| _activate_runtime() | |
| if device == 'auto': | |
| device = 'cuda' if torch.cuda.is_available() else 'cpu' | |
| if implementation == 'd5a': | |
| module_name = 'scaling_impl.phase_d.source_compiler_d5a' | |
| class_name = 'SourceCompiler' | |
| elif implementation in ('d5-final', 'd5_final'): | |
| module_name = 'scaling_impl.phase_d.source_compiler_d5_final' | |
| class_name = 'FinalSourceCompiler' | |
| else: | |
| raise ValueError('implementation must be d5a or d5-final') | |
| compiler_class = getattr(importlib.import_module(module_name), class_name) | |
| self.device = torch.device(device) | |
| self.implementation = 'd5-final' if implementation != 'd5a' else 'd5a' | |
| memory_path = (RUNTIME_ROOT / 'runs' / 'hyperopt_h1_h3' / | |
| 'ssa_memory.pt') if use_ssa_memory else None | |
| self._compiler = compiler_class.load_pinned( | |
| device=self.device, | |
| root=RUNTIME_ROOT, | |
| release=RUNTIME_ROOT / 'release', | |
| syntax_weights=RUNTIME_ROOT / 'phase_c_results.pt', | |
| span_chunk=span_chunk, | |
| compact=compact, | |
| encoder_chunk=encoder_chunk, | |
| ssa_memory_path=memory_path, | |
| ) | |
| self.use_ssa_memory = use_ssa_memory | |
| self.hyperopt = bool(hyperopt) | |
| self.mode = 'hyperoptimization' if self.hyperopt else 'ordinary' | |
| self._hyperoptimizer = None | |
| if self.hyperopt: | |
| from scaling_impl.hyperopt import H7Optimizer | |
| self._hyperoptimizer = H7Optimizer( | |
| self._compiler, | |
| RUNTIME_ROOT / 'runs' / 'hyperopt_h7', | |
| ) | |
| def from_pretrained(cls, package_root=None, **kwargs): | |
| """Construct from this package or an unpacked 0.4.0 release tree.""" | |
| if package_root is not None: | |
| raise ValueError('package_root is not supported by the wheel API; install the release') | |
| return cls(**kwargs) | |
| def compile_batch(self, sources: Sequence[str], *, evidence=True): | |
| """Compile source strings in original lane order. | |
| Returns one :class:`CompilationResult` per input. Invalid lanes have | |
| ``valid=False`` and empty bytes. No reference labels or native | |
| execution are involved. | |
| """ | |
| sources = [sources] if isinstance(sources, str) else list(sources) | |
| if self._hyperoptimizer is not None: | |
| packed = self._hyperoptimizer.compile_batch(sources) | |
| out = [] | |
| for code, size, valid, record in packed: | |
| out.append(CompilationResult(valid=valid, code=code, | |
| size=size if valid else 0, | |
| record=dict(record))) | |
| return out | |
| packet, records = self._compiler.compile_for_neurold( | |
| sources, evidence=evidence) | |
| if not sources: | |
| return [] | |
| valid = packet['valid'].detach().cpu() | |
| sizes = packet['size'].detach().cpu() | |
| code = packet['code'].detach().cpu() | |
| out = [] | |
| for lane, record in enumerate(records): | |
| ok = bool(valid[lane]) | |
| size = int(sizes[lane]) if ok else 0 | |
| out.append(CompilationResult( | |
| valid=ok, | |
| code=bytes(code[lane, :size].tolist()) if ok else b'', | |
| size=size, | |
| record=dict(record), | |
| )) | |
| return out | |
| def compile_source(self, source: str, *, evidence=True): | |
| """Compile one source string and return its lane-aligned result.""" | |
| return self.compile_batch([source], evidence=evidence)[0] | |
| def checkpoint_manifest(): | |
| """Return the shipped checkpoint manifest and hashes.""" | |
| return json.loads((PACKAGE_ROOT / 'manifest.json').read_text(encoding='utf-8')) | |