"""Shared compilation and input allocation for model and warp artifacts.""" import io, pathlib, pickle, shutil, struct, time, tempfile import numpy as np from typing import Callable from tinygrad import Tensor, Device, Context from tinygrad.device import Buffer from tinygrad.uop.ops import PatternMatcher, UPat, Ops, graph_rewrite from tinygrad.nn.state import get_parameters def allocate_inputs(input_specs, initialize=None): """Initialize inputs before copying to devices.""" arrays = {name: np.zeros(shape, dtype=dtype) for name, (shape, dtype, _) in input_specs.items()} if initialize is not None: initialize(arrays) return {name: Tensor(arrays[name], device=device).realize() for name, (_, _, device) in input_specs.items()} def dump_pickle(obj, path): with tempfile.TemporaryFile(dir=".") as buffers: opcodes, offset = io.BytesIO(), 0 def persistent_id(b): nonlocal offset if not isinstance(b, Buffer) or b.device != Device.DEFAULT: return None offset += buffers.write(bytes((-offset) % 256)) offset = (off:=offset) + buffers.write(b.as_memoryview()) return b.nbytes, off p = pickle.Pickler(opcodes) p.persistent_id = persistent_id p.dump(obj) with open(path, "wb") as f: f.write(struct.pack('