repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
tinygrad
extra/torch_backend/test_kernel_fusion.py
.py
# simple tests import unittest import torch from tinygrad.helpers import getenv, GlobalCounters if getenv("TINY_BACKEND2"): import extra.torch_backend.backend2 device = "cpu" else: import extra.torch_backend.backend device = "tiny" class TestKernelFusionRegression(unittest.TestCase): def _realize(self, t): ...
142
4,390
tinygrad
extra/torch_backend/torch_tests.py
.py
import sys import unittest import torch import extra.torch_backend.backend from torch.testing._internal.common_utils import TestCase, is_privateuse1_backend_available assert is_privateuse1_backend_available() and torch._C._get_privateuse1_backend_name() == "tiny" from torch.testing._internal.common_device_type import ...
44
1,916
tinygrad
extra/torch_backend/test_compile.py
.py
# https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html import torch import torch._dynamo from extra.torch_backend.backend import unwrap, wrap from torch._dynamo.backends.registry import register_backend from torch._functorch.aot_autograd import aot_module_simplified from tinygrad import Tensor, Tiny...
37
1,386
tinygrad
extra/torch_backend/backend2.py
.py
# NOTE: this is probably the wrong backend to work on, you want backend.py # discussion about this in #pytorch-backend on our Discord # this is using high level debug features from torch and we should integrate deeper from tinygrad import Tensor import torch, contextlib from torch.utils._python_dispatch import TorchDi...
48
2,090
tinygrad
extra/torch_backend/test_multigpu.py
.py
import unittest from tinygrad.helpers import getenv import torch import tinygrad.nn.torch import numpy as np @unittest.skipIf(getenv("GPUS",1)<=1, "only single GPU") class TestTorchBackendMultiGPU(unittest.TestCase): def setUp(self): self._prev_device = torch.get_default_device() torch.set_default_device("ti...
34
1,085
tinygrad
extra/torch_backend/test.py
.py
# simple tests import unittest import torch import numpy as np from tinygrad.helpers import getenv, GlobalCounters if getenv("TINY_BACKEND2"): import extra.torch_backend.backend2 device = "cpu" else: import extra.torch_backend.backend device = "tiny" class TestTorchBackend(unittest.TestCase): def test_randpe...
1,033
43,306
tinygrad
extra/torch_backend/test_inplace.py
.py
import unittest import torch import tinygrad.nn.torch import numpy as np class TestTorchBackendInplace(unittest.TestCase): def setUp(self): self._prev_device = torch.get_default_device() torch.set_default_device("tiny") def tearDown(self): torch.set_default_device(self._prev_device) def test_zero(self):...
108
3,415
tinygrad
extra/torch_backend/backend.py
.py
# ruff: noqa: E501, A001, A002, A006 # A001 Variable `input` is shadowing a Python builtin # A002 Function argument `input` is shadowing a Python builtin # A006 Lambda argument `input` is shadowing a Python builtin from tinygrad import Tensor, dtypes, Device from tinygrad.uop.ops import Ops, GroupOp from tinygrad.helpe...
791
40,119
tinygrad
extra/hip_gpu_driver/test_kfd_2.py
.py
import os, ctypes, pathlib, re, fcntl, functools, mmap, time import tinygrad.runtime.autogen.kfd as kfd from tinygrad.helpers import to_mv, getenv from extra.hip_gpu_driver import hip_ioctl import tinygrad.runtime.autogen.hsa as hsa from hexdump import hexdump libc = ctypes.CDLL("libc.so.6") libc.memset.argtypes = [ct...
208
12,093
tinygrad
extra/hip_gpu_driver/hip_ioctl.py
.py
# type: ignore import ctypes, ctypes.util, struct, platform, pathlib, re, time, os start = time.perf_counter() # *** ioctl lib *** libc = ctypes.CDLL(ctypes.util.find_library("c")) # platform.processor calls `uname -p` which can return `unknown` on some systems processor = os.getenv("IOCTL_PROCESSOR") or platform.proc...
118
5,104
tinygrad
extra/hip_gpu_driver/test_pm4.py
.py
import time from hexdump import hexdump from tinygrad import Tensor, Device import tinygrad.runtime.autogen.amd_gpu as amd_gpu import tinygrad.runtime.autogen.kfd as kfd import tinygrad.runtime.autogen.hsa as hsa from tinygrad.runtime.ops_amd import kio, AMDProgram from tinygrad.helpers import to_mv DISPATCH_INIT_VALU...
157
6,181
tinygrad
extra/hip_gpu_driver/test_sdma_fun.py
.py
import ctypes, mmap, time from tinygrad.runtime.ops_amd import AMDDevice, kio, sdma_pkts, libc import tinygrad.runtime.autogen.amd_sdma as amd_sdma import tinygrad.runtime.autogen.kfd as kfd from tinygrad.helpers import to_mv if __name__ == "__main__": dev = AMDDevice() sdma_ring = dev._gpu_alloc(1 << 22, kfd.KFD...
44
2,135
tinygrad
extra/amdpci/proclogs.py
.py
import re, ctypes, sys, importlib from tinygrad.helpers import getenv from tinygrad.runtime.support.am.amdev import AMDev, AMRegister class GFXFake: def __init__(self): self.xccs = 8 class AMDFake(AMDev): def __init__(self, pci_dev): self.pci_dev, self.devfmt = pci_dev, pci_dev.pcibus self.vram, self.doo...
97
3,228
tinygrad
extra/amdpci/am_smi.py
.py
#!/usr/bin/env python3 import time, mmap, sys, shutil, os, glob, subprocess, argparse, collections from tinygrad.helpers import DEBUG, NO_COLOR, colored, ansilen from tinygrad.runtime.autogen import libc from tinygrad.runtime.autogen.am import am from tinygrad.runtime.support.hcq import MMIOInterface from tinygrad.run...
417
18,704
tinygrad
extra/amdpci/hive_reset.py
.py
#!/usr/bin/env python3 import os from tinygrad.helpers import Context from tinygrad.runtime.support.system import System, PCIDevice from tinygrad.runtime.support.hcq import FileIOInterface from tinygrad.runtime.support.am.amdev import AMDev if __name__ == "__main__": gpus = System.pci_scan_bus(0x1002, [(0xffff, [0x...
21
790
tinygrad
docs/abstractions4.py
.py
# tinygrad allows you to write kernels at many different abstractions levels. # This is for RDNA3, but if you don't have one you can run with the emulator # PYTHONPATH="." DEV=MOCKPCI+AMD from tinygrad import Tensor, Context, GlobalCounters, UOp, Device from tinygrad.helpers import DEV, DEBUG, getenv from tinygrad.uop...
252
11,521
tinygrad
docs/abstractions3.py
.py
# abstractions2 goes from back to front, here we will go from front to back # ***** # 0. Load mnist on the device from tinygrad.nn.datasets import mnist X_train, Y_train, _, _ = mnist() X_train = X_train.float() X_train -= X_train.mean() # ***** # 1. Define an MNIST model. from tinygrad import Tensor, Context l1 =...
55
1,486
tinygrad
tinygrad/device.py
.py
from __future__ import annotations from dataclasses import dataclass, replace from collections import defaultdict from typing import Any, Generic, TypeVar, Iterator, Generator, Self, TYPE_CHECKING import importlib, inspect, functools, pathlib, os, contextlib, re, atexit, pickle, decimal from tinygrad.helpers import LRU...
431
23,303
tinygrad
tinygrad/tensor.py
.py
# inspired by https://github.com/karpathy/micrograd/blob/master/micrograd/engine.py from __future__ import annotations import time, functools, sys, inspect, pathlib, hashlib, weakref from dataclasses import dataclass, field from typing import Any, Callable, cast, get_args, ParamSpec, TypeGuard, TypeVar, Generic, TYPE_C...
776
38,101
tinygrad
tinygrad/function.py
.py
import functools, time from dataclasses import replace from typing import Generic, TypeVar, Callable, cast, overload from tinygrad.helpers import Context, dedup, getenv, DEBUG from tinygrad.uop.ops import UOp, Ops, graph_rewrite, PatternMatcher, UPat from tinygrad.tensor import Tensor from tinygrad.nn.state import get_...
106
5,179
tinygrad
tinygrad/helpers.py
.py
from __future__ import annotations import time START_TIME = time.perf_counter() import os, functools, re, contextlib, operator, hashlib, pickle, sqlite3, tempfile, pathlib, string, ctypes, sys, gzip, getpass, gc from collections import defaultdict import shutil, math, types, copyreg, inspect, importlib, decimal, iterto...
623
33,356
tinygrad
tinygrad/dtype.py
.py
from __future__ import annotations from typing import Final, ClassVar, Callable, Literal import math, struct, ctypes, functools from dataclasses import dataclass, fields from tinygrad.helpers import getenv, DEFAULT_FLOAT, DEFAULT_INT from enum import IntEnum, auto class ConstFloat(float): """Float subclass that dist...
325
17,133
tinygrad
tinygrad/schedule/indexing.py
.py
from typing import Iterator import functools, itertools from dataclasses import dataclass, field, replace from tinygrad.dtype import dtypes, AddrSpace from tinygrad.uop.ops import PatternMatcher, UPat, Ops, UOp, resolve, GroupOp, graph_rewrite, sint, AxisType, rewrite_group, broadcast_axes from tinygrad.uop.ops import ...
334
16,712
tinygrad
tinygrad/schedule/__init__.py
.py
import time, inspect from collections import deque from tinygrad.uop.ops import UOp, Ops, UOpMetaClass, rewrite_group, graph_rewrite, gate_kernel_sink, KernelInfo from tinygrad.uop.spec import type_verify, spec_tensor from tinygrad.helpers import DEBUG, cpu_profile, TracingKey, SPEC, pluralize, SCACHE, BASEDIR, partiti...
204
10,641
tinygrad
tinygrad/schedule/rangeify.py
.py
from dataclasses import dataclass, field, replace from typing import cast import itertools from tinygrad.dtype import dtypes, AddrSpace, Invalid, to_dtype, strong_dtype from tinygrad.uop.ops import PatternMatcher, UPat, Ops, UOp, resolve, GroupOp, KernelInfo, ParamArg, shape_to_shape_arg from tinygrad.uop.ops import gr...
605
30,957
tinygrad
tinygrad/schedule/multi.py
.py
from tinygrad.helpers import all_same, prod, getenv, ALLREDUCE_CAST from tinygrad.uop.ops import Ops, UOp, PatternMatcher, UPat, GroupOp, AxisType, graph_rewrite, broadcast_axes, _broadcast_shape, sint_to_uop from tinygrad.uop.ops import sint, ssimplify from tinygrad.dtype import dtypes from tinygrad.schedule.allreduce...
320
18,804
tinygrad
tinygrad/schedule/allreduce.py
.py
import functools, itertools from tinygrad.helpers import all_int, prod, DEBUG, RING, ALL2ALL, getenv from tinygrad.uop.ops import UOp # *** allreduce implementation *** def handle_allreduce(buf:UOp, red:UOp) -> UOp|None: if not isinstance(buf.device, tuple): return None ndev, shape, numel = len(buf.device), buf.sh...
66
3,420
tinygrad
tinygrad/schedule/memory.py
.py
from collections import defaultdict from tinygrad.helpers import NO_MEMORY_PLANNER, DEBUG, round_up from tinygrad.uop.ops import UOp, Ops from tinygrad.dtype import dtypes from tinygrad.runtime.support.memory import TLSFAllocator def _collect_bufs(u:UOp) -> list[UOp]: if u.op is Ops.BUFFER: return [u] if u.op in {...
63
3,295
tinygrad
tinygrad/nn/state.py
.py
import json, math, pathlib, struct, functools, io, zlib from collections import OrderedDict from typing import Any, Callable, BinaryIO, Iterable, cast from tinygrad.tensor import Tensor from tinygrad.dtype import dtypes from tinygrad.helpers import prod, argsort, DEBUG, Timing, GlobalCounters, tqdm, round_up, T, stride...
353
16,011
tinygrad
tinygrad/nn/datasets.py
.py
from tinygrad.tensor import Tensor from tinygrad.nn.state import tar_extract def mnist(device=None, fashion=False): base_url = "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/" if fashion else "https://storage.googleapis.com/cvdf-datasets/mnist/" def _mnist(file): return Tensor.from_url(base_url+file, ...
15
1,059
tinygrad
tinygrad/nn/optim.py
.py
# sorted in order of increasing complexity import itertools from tinygrad.helpers import dedup, flatten, getenv, unwrap, FUSE_OPTIM, TRAINING from tinygrad.tensor import Tensor from tinygrad.dtype import dtypes, least_upper_dtype, to_dtype class Optimizer: """ Base class for all optimizers. """ def __init__(se...
180
9,342
tinygrad
tinygrad/nn/__init__.py
.py
from __future__ import annotations import math, functools from tinygrad.tensor import Tensor from tinygrad.dtype import dtypes from tinygrad.helpers import prod, make_tuple, flatten, USE_ATOMICS, TRAINING from tinygrad.nn import optim, state, datasets # noqa: F401 class BatchNorm: """ Applies Batch Normalization ...
421
18,571
tinygrad
tinygrad/nn/torch.py
.py
# type: ignore import sys, pathlib sys.path.append(pathlib.Path(__file__).parent.parent.as_posix()) try: import extra.torch_backend.backend # noqa: F401 # pylint: disable=unused-import except ImportError as e: raise ImportError("torch frontend not in release\nTo fix, install tinygrad from a git checkout with pip insta...
5
336
tinygrad
tinygrad/nn/onnx.py
.py
# pylint: disable=possibly-unused-variable from typing import Any, Sequence, cast, Literal, NamedTuple, Generator import dataclasses, functools, io, math, types, warnings, pathlib, sys, os, struct, enum from tinygrad.nn.state import TensorIO from tinygrad.tensor import Tensor, is_numpy_ndarray from tinygrad.mixin.op im...
1,312
75,683
tinygrad
tinygrad/llm/model.py
.py
from __future__ import annotations import functools, itertools, pathlib from dataclasses import dataclass, replace from tinygrad import Tensor, nn, UOp, TinyJit, getenv, function, dtypes from tinygrad.nn import Linear from tinygrad.llm.gguf import gguf_load from tinygrad.uop.ops import resolve @functools.cache def pre...
453
27,328
tinygrad
tinygrad/llm/gguf.py
.py
import functools, io, pathlib, re, struct from typing import Any, Callable from tinygrad.tensor import Tensor from tinygrad.dtype import dtypes from tinygrad.helpers import prod, round_up from tinygrad.nn.state import TensorIO # ggml packs each iq grid entry as N bytes (N=4 for uint32 grids, N=8 for uint64 grids) in ...
177
11,615
tinygrad
tinygrad/llm/serve.py
.py
from __future__ import annotations import json, pathlib, re, time, typing, uuid from typing import TYPE_CHECKING from tinygrad.helpers import DEBUG, colored, stderr_log from tinygrad.viz.serve import TCPServerWithReuse, HTTPRequestHandler if TYPE_CHECKING: from tinygrad.llm.cli import SimpleTokenizer from tinygrad....
168
9,547
tinygrad
tinygrad/llm/cli.py
.py
from __future__ import annotations import sys, argparse, codecs, itertools, typing, re, unicodedata, json, time from typing import TYPE_CHECKING from tinygrad import nn from tinygrad.uop.ops import UOp, Ops from tinygrad.helpers import partition, DEBUG, Timing, GlobalCounters, Context, fetch, profile_marker, getenv fro...
204
12,586
tinygrad
tinygrad/codegen/__init__.py
.py
from dataclasses import replace, dataclass import itertools, functools from tinygrad.helpers import DISABLE_FAST_IDIV, TRANSCENDENTAL, SPEC, DEBUG, VIZ, IMAGE, NOOPT, EMULATED_DTYPES, NOLOCALS, USE_TC from tinygrad.helpers import ALLOW_TF32, DEFAULT_FLOAT, DEFAULT_INT, TracingKey, Context, panic from tinygrad.uop.ops i...
489
24,657
tinygrad
tinygrad/codegen/simplify.py
.py
import itertools from typing import Callable from tinygrad.uop.ops import UOp, PatternMatcher, UPat, Ops, graph_rewrite, _substitute, range_start, AxisType from tinygrad.uop.symbolic import symbolic, invalid_gate from tinygrad.helpers import partition from tinygrad.dtype import dtypes def flatten_range(r:UOp) -> UOp|N...
160
8,799
tinygrad
tinygrad/codegen/gpudims.py
.py
import math from tinygrad.uop.ops import UOp, Ops, sint, PatternMatcher, UPat, KernelInfo, ssimplify, AxisType from tinygrad.dtype import dtypes, AddrSpace from tinygrad.renderer import Renderer def _dim_max(d:sint) -> int: return d if isinstance(d, int) else int(d.vmax) def _group_dims(dims:tuple[sint, ...], max_siz...
102
5,197
tinygrad
tinygrad/codegen/decomp/transcendental.py
.py
from typing import Callable import math, functools from tinygrad.dtype import dtypes, DType from tinygrad.helpers import polyN from tinygrad.uop.ops import UOp, UPat, Ops, PatternMatcher TRANSCENDENTAL_DTYPES = (dtypes.float16, dtypes.float32, dtypes.float64) def _lazy_map_numbers(x:UOp, inf:UOp, _inf:UOp, nan:UOp, r...
278
14,510
tinygrad
tinygrad/codegen/decomp/op.py
.py
from typing import Callable import functools from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp, UPat, Ops, PatternMatcher from tinygrad.renderer import Renderer # *** integer division *** @functools.lru_cache(None) def magicgu(vmax:int, d:int) -> tuple[int,int]: # calculate m,s such that x//d == (x...
134
8,246
tinygrad
tinygrad/codegen/decomp/dtype.py
.py
from dataclasses import replace from tinygrad.dtype import dtypes, DType, truncate from tinygrad.helpers import flatten, DEBUG, EMULATED_DTYPES, Context, SPEC from tinygrad.uop import GroupOp from tinygrad.uop.ops import UOp, UPat, Ops, PatternMatcher, graph_rewrite, ParamArg from tinygrad.renderer import Renderer from...
214
15,240
tinygrad
tinygrad/codegen/late/coalesce.py
.py
import itertools, functools from collections import defaultdict from tinygrad.dtype import dtypes, AddrSpace, Invalid, DType from tinygrad.uop.ops import UOp, Ops, PatternMatcher, UPat, GroupOp, shape_to_shape_arg, graph_rewrite from tinygrad.uop.symbolic import uop_given_valid, parse_valid, invalid_gate, sym from tiny...
169
9,290
tinygrad
tinygrad/codegen/late/linearizer.py
.py
import heapq from typing import Any from collections import defaultdict from tinygrad.uop.ops import PatternMatcher, UOp, Ops, UPat, multirange_str from tinygrad.dtype import AddrSpace, dtypes from tinygrad.helpers import prod, getenv, TUPLE_ORDER def linearize(sink:UOp) -> list[UOp]: # this is a toposort with prior...
96
4,113
tinygrad
tinygrad/codegen/late/gater.py
.py
# this is a temporary intermediate step while we remove this index style from tinygrad.uop.ops import PatternMatcher, UPat, Ops from tinygrad.dtype import Invalid, dtypes def move_where_load(gate, l, a, w): return l.replace(src=(l.src[0], l.vconst_like(0) if a.is_invalid else l.const_like(a.val) if a.op is Ops.CONST...
30
2,078
tinygrad
tinygrad/codegen/late/regalloc.py
.py
import itertools from tinygrad.helpers import dedup from tinygrad.uop.ops import UOp, Ops, PatternMatcher, UPat from tinygrad.renderer.isa import ISARenderer, Register, greg from tinygrad.dtype import dtypes PSEUDO_OPS = {Ops.CONST, Ops.NOOP, Ops.AFTER, Ops.BARRIER, Ops.GROUP, Ops.STACK} class LinearScanRegallocConte...
137
7,164
tinygrad
tinygrad/codegen/opt/__init__.py
.py
# opt opinionatedly transforms an ast into an optimized ast using either heuristics or beam search from __future__ import annotations from enum import Enum, auto from dataclasses import dataclass class OptOps(Enum): TC = auto(); UPCAST = auto(); UNROLL = auto(); LOCAL = auto(); THREAD = auto() # noqa: E702 GROUP =...
21
780
tinygrad
tinygrad/codegen/opt/postrange.py
.py
from __future__ import annotations import math, itertools from collections import defaultdict from typing import cast, Final from tinygrad.uop.ops import Ops, UOp, KernelInfo, graph_rewrite, AxisType, ssimplify, remove_all_tags from tinygrad.uop.ops import axis_letters, axis_colors, axis_to_pos from tinygrad.device imp...
357
20,893
tinygrad
tinygrad/codegen/opt/search.py
.py
import math, time, multiprocessing, traceback, signal, atexit from dataclasses import replace from tinygrad.uop.ops import sym_infer, AxisType, UOp, Ops from tinygrad.uop.render import pyrender from tinygrad.device import Device, Buffer from tinygrad.helpers import prod, flatten, DEBUG, CACHELEVEL, diskcache_get, diskc...
188
10,217
tinygrad
tinygrad/codegen/opt/tc.py
.py
import math, functools from dataclasses import dataclass from tinygrad.dtype import DType, dtypes from tinygrad.uop.ops import PatternMatcher, UOp, UPat, Ops @dataclass(frozen=True) class TensorCore: # D = A * B + C, A is (M x K), B is (K x N), C and D are (M x N) dims: tuple[int,int,int] # N, M, K threads: int # ...
183
12,771
tinygrad
tinygrad/codegen/opt/heuristic.py
.py
import itertools from tinygrad.codegen.opt import Opt, OptOps, KernelOptError from tinygrad.helpers import getenv, DEBUG, prod, NOLOCALS, TC_OPT, TC_SELECT, USE_TC, IMAGE from tinygrad.uop.ops import Ops, resolve, AxisType from tinygrad.codegen.late.coalesce import image_valid_dims from tinygrad.codegen.opt.postrange i...
195
11,585
tinygrad
tinygrad/renderer/wgsl.py
.py
from tinygrad.dtype import DType, dtypes, truncate, AddrSpace from tinygrad.uop.ops import UOp, Ops, PatternMatcher, UPat from tinygrad.renderer.cstyle import CStyleLanguage, base_rewrite from tinygrad.helpers import strip_parens def _mask(dt:DType): return 0xFF if dt.itemsize == 1 else 0xFFFF def sign_extend(val:UOp...
119
8,795
tinygrad
tinygrad/renderer/__init__.py
.py
from __future__ import annotations from typing import Callable, cast from dataclasses import dataclass from tinygrad.helpers import prod, Target, EMULATED_DTYPES from tinygrad.uop.ops import Ops, UOp, sint, ssimplify, smin, GroupOp, PatternMatcher from tinygrad.dtype import AddrSpace, DType, dtypes from tinygrad.codege...
85
4,274
tinygrad
tinygrad/renderer/cstyle.py
.py
from typing import Literal, Callable import math, sys, struct from collections import defaultdict, Counter from tinygrad.codegen.opt import tc from tinygrad.uop.ops import GroupOp, Ops, UOp, PatternMatcher, UPat, range_str, axis_letters from tinygrad.helpers import strip_parens, getenv, prod, dedup, Target, NUM_CPU_THR...
606
39,120
tinygrad
tinygrad/renderer/nir.py
.py
from typing import Callable, Any from tinygrad.dtype import AddrSpace, DType, dtypes, truncate from tinygrad.helpers import DEBUG, OSX, unwrap, fromimport, Target, is_image_shape, round_up from tinygrad.renderer import Renderer from tinygrad.renderer.cstyle import CUDARenderer from tinygrad.uop.ops import GroupOp, Ops,...
326
21,649
tinygrad
tinygrad/renderer/llvmir.py
.py
import math, struct, sys from tinygrad.codegen.opt import tc from tinygrad.renderer import Renderer from tinygrad.renderer.cstyle import HIPRenderer, create_non_native_float_pats, pm_manual_bf16_cast from tinygrad.codegen.decomp.transcendental import xexp2, xlog2 from tinygrad.uop.ops import UOp, PatternMatcher, UPat, ...
288
18,291
tinygrad
tinygrad/renderer/ptx.py
.py
from typing import cast, Callable import struct from collections import defaultdict from tinygrad.codegen.opt import tc from tinygrad.uop.ops import Ops, UOp, PatternMatcher, UPat, GroupOp from tinygrad.dtype import dtypes, DType, AddrSpace from tinygrad.renderer import Renderer from tinygrad.renderer.cstyle import CUD...
234
16,370
tinygrad
tinygrad/renderer/isa/__init__.py
.py
from __future__ import annotations import itertools from dataclasses import dataclass, field from tinygrad.renderer import Renderer from tinygrad.uop.ops import PatternMatcher, UOp, Ops, consumer_map_from_toposort @dataclass(frozen=True) class Register: name: str index: int _cons: tuple[Register, ...] = field(de...
51
1,968
tinygrad
tinygrad/renderer/isa/x86.py
.py
# flake8: noqa: E702 # allow semicolons to put multiple ops on one line import sys, struct, functools from typing import cast from tinygrad.dtype import dtypes, DType, truncate, AddrSpace from tinygrad.uop import FastEnum, auto, Ops, GroupOp from tinygrad.uop.ops import UOp, UPat, PatternMatcher from tinygrad.renderer....
882
63,413
tinygrad
tinygrad/renderer/amd/generate.py
.py
# AMD ISA code generator - generates enum.py, ins.py, operands.py, str_pcode.py # Sources: XML from https://gpuopen.com/download/machine-readable-isa/latest/ # PDF manuals from AMD documentation import re, zlib, xml.etree.ElementTree as ET, zipfile, pathlib from tinygrad.helpers import fetch # ═══════════════...
532
33,498
tinygrad
tinygrad/renderer/amd/elf.py
.py
# minimal amdgpu elf packer import ctypes from tinygrad.dtype import AddrSpace from tinygrad.helpers import ceildiv, round_up from tinygrad.uop.ops import UOp, Ops from tinygrad.runtime.autogen import amdgpu_kd, hsa, libc from tinygrad.renderer.amd.dsl import Reg, FixedBitField from tinygrad.runtime.autogen.amd.common ...
112
6,420
tinygrad
tinygrad/renderer/amd/__init__.py
.py
# Instruction format detection and decoding from __future__ import annotations from tinygrad.renderer.amd.dsl import Inst, FixedBitField, EnumBitField # SDWA/DPP variant detection: src0 field (bits 0-8) encodes the variant # 0xf9 (249) = SDWA, 0xfa (250) = DPP16 for CDNA (GFX9) _VARIANT_SRC0 = {"_SDWA_SDST": 0xf9, "_S...
76
4,925
tinygrad
tinygrad/renderer/amd/sqtt.py
.py
"""SQTT (SQ Thread Trace) packet encoder and decoder for AMD GPUs. This module provides encoding and decoding of raw SQTT byte streams. The format is nibble-based with variable-width packets determined by a state machine. Uses BitField infrastructure from dsl.py, similar to GPU instruction encoding. """ from __future_...
746
28,263
tinygrad
tinygrad/renderer/amd/dsl.py
.py
# dsl.py - clean DSL for AMD assembly from typing import Any # ══════════════════════════════════════════════════════════════ # Registers - unified src encoding space (0-511) # ══════════════════════════════════════════════════════════════ class Reg: # Register names vary by arch: RDNA has NULL@124/M0@125, CDNA has...
457
24,397
tinygrad
tinygrad/engine/jit.py
.py
from typing import TypeVar, Generic, Callable, Any, overload import functools from tinygrad.tensor import Tensor, all_tensors from tinygrad.helpers import flatten, merge_dicts, DEBUG, Context, BEAM, getenv, JIT, JIT_BATCH_SIZE, dedup, pluralize, VIZ, disable_gc from tinygrad.device import Buffer, Compiled, Device, Mult...
295
15,799
tinygrad
tinygrad/engine/realize.py
.py
from __future__ import annotations from typing import cast, Iterator, Any, Sequence import time, random, itertools, math, contextlib, weakref, array from dataclasses import dataclass, replace, field from tinygrad.helpers import colored, DEBUG, GlobalCounters, ansilen, all_int, prod, flatten, Context, getenv, to_tuple f...
291
17,863
tinygrad
tinygrad/viz/serve.py
.py
#!/usr/bin/env python3 import multiprocessing, pickle, difflib, os, threading, json, time, sys, webbrowser, socket, argparse, codecs, io, struct, re, traceback, itertools import socketserver from contextlib import redirect_stdout, redirect_stderr, contextmanager from decimal import Decimal from dataclasses import datac...
740
41,148
tinygrad
tinygrad/viz/cli.py
.py
#!/usr/bin/env python3 import argparse, pathlib, signal, struct, json, os, itertools, heapq os.environ["VIZ"] = "0" if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_DFL) from typing import Iterator from tinygrad.viz import serve as viz from tinygrad.viz.serve import fmt_colored from tinygrad.uop....
236
14,095
tinygrad
tinygrad/uop/movement.py
.py
from tinygrad.uop.ops import PatternMatcher, UPat, Ops # TODO: pm_mops from rangeify belongs here. this is all pattern matchers that strictly clean up movement ops mop_cleanup = PatternMatcher([ # merge adjacent RESHAPES (UPat(Ops.RESHAPE, src=(UPat(Ops.RESHAPE, name="x2"), UPat()), name="x"), lambda x,x2: x.repl...
27
1,857
tinygrad
tinygrad/uop/render.py
.py
from tinygrad.dtype import AddrSpace, dtypes from tinygrad.uop import Ops, GroupOp from tinygrad.uop.ops import ParamArg, UOp, PatternMatcher, UPat, multirange_str, range_str, consumer_map_from_toposort from tinygrad.helpers import strip_parens def pretty_print(x:UOp, cache=None, d=0)->str: def dfs(x:UOp, cache:dict...
162
10,386
tinygrad
tinygrad/uop/divandmod.py
.py
import functools, itertools, math from tinygrad.uop.ops import PatternMatcher, UPat, Ops, UOp from tinygrad.dtype import dtypes from tinygrad.helpers import unwrap # NOTE: this cache is only on index UOps @functools.cache def fold_divmod_general(d: UOp) -> UOp|None: x, y = d.src if y.vmin==y.vmax==0: raise ZeroDi...
110
5,505
tinygrad
tinygrad/uop/__init__.py
.py
# flake8: noqa: E702 # allow semicolons to put multiple ops on one line from enum import auto, IntEnum, Enum # wrapper around IntEnum that preserves Enum.__str__ and makes auto() unique across all FastEnum subclasses class FastEnum(IntEnum): def __str__(self): return Enum.__str__(self) def __repr__(x): return str(...
138
4,774
tinygrad
tinygrad/uop/ops.py
.py
from __future__ import annotations from typing import Any, Callable, cast, TYPE_CHECKING, Type, Sequence, Iterable, Final, Iterator import sys, time, functools, itertools, math, operator, hashlib, os, types, pickle, pathlib, inspect, weakref, collections, struct from dataclasses import dataclass, replace from enum impo...
1,786
99,521
tinygrad
tinygrad/uop/spec.py
.py
import math from typing import Any from tinygrad.uop.ops import PatternMatcher, UPat, GroupOp, Ops, UOp, AxisType, KernelInfo, ParamArg from tinygrad.uop.render import print_uops, pyrender from tinygrad.dtype import DType, dtypes, AddrSpace, Invalid, ConstFloat from tinygrad.helpers import DEBUG, Context, SPEC, Metadat...
296
16,641
tinygrad
tinygrad/uop/upat.py
.py
from typing import Any, Callable import itertools, inspect, functools, types from tinygrad.helpers import partition, dedup, Context from tinygrad.uop.ops import UPat, UOp, Ops, PatternMatcher, graph_rewrite, deconstruct_function class UPatCompileError(Exception): pass # **** UPat compiled **** # This file builds an I...
172
8,165
tinygrad
tinygrad/uop/validate.py
.py
from typing import Callable from tinygrad.uop.ops import PatternMatcher, UPat, GroupOp, Ops, UOp, python_alu from tinygrad.dtype import dtypes, Invalid from tinygrad.helpers import cpu_profile import z3 # older versions of z3 dont have some operators like & overloaded if z3.get_version() < (4, 12, 4, 0): raise Impor...
90
5,958
tinygrad
tinygrad/uop/symbolic.py
.py
# all of symbolic lives here now import math from collections import defaultdict from tinygrad.uop.ops import Ops, PatternMatcher, UPat, UOp, GroupOp, exec_alu from tinygrad.dtype import PyConst, ConstType, dtypes, can_lossless_cast, Invalid, bitcast from tinygrad.helpers import partition, all_same, prod, flatten, unwr...
463
30,451
tinygrad
tinygrad/uop/weak.py
.py
from dataclasses import replace from tinygrad.dtype import dtypes, DType, AddrSpace, Invalid, least_upper_dtype, strong_dtype, weak_dtype from tinygrad.helpers import unwrap from tinygrad.uop.ops import UOp, UPat, Ops, PatternMatcher, GroupOp, graph_rewrite, dtype_from_uop def select_dtype(u:UOp): if u.dtype is dtyp...
83
5,531
tinygrad
tinygrad/runtime/ops_rdma.py
.py
from __future__ import annotations import mmap, struct, functools from typing import cast from tinygrad.uop.ops import sint from tinygrad.runtime.support.hcq import HCQCompiled, HCQAllocatorBase, HCQAllocator, HWQueue, HCQBuffer, FileIOInterface from tinygrad.runtime.support.system import System, PCIIfaceBase, PCIAlloc...
107
6,159
tinygrad
tinygrad/runtime/ops_qcom.py
.py
from __future__ import annotations import os, ctypes, functools, mmap, struct, array, math, sys, weakref, contextlib assert sys.platform != 'win32' from typing import Any, cast from tinygrad.device import BufferSpec, Device, TinyELF from tinygrad.runtime.support.hcq import HCQBuffer, HWQueue, HCQProgram, HCQCompiled, H...
416
26,139
tinygrad
tinygrad/runtime/ops_disk.py
.py
import os, sys, mmap, io, ctypes, contextlib, pathlib from typing import Generator, Callable from tinygrad.helpers import OSX, round_up from tinygrad.device import Compiled, Allocator with contextlib.suppress(ImportError): import _posixshmem from tinygrad.runtime.autogen import io_uring, libc class DiskDevice(Comp...
143
7,620
tinygrad
tinygrad/runtime/ops_webgpu.py
.py
import functools, struct from tinygrad.device import Compiled, Allocator, BufferSpec, Program, TinyELF from tinygrad.renderer.wgsl import WGSLRenderer from tinygrad.helpers import round_up, suppress_finalizing, getenv, to_mv from tinygrad.runtime.autogen import webgpu from tinygrad.runtime.support import c from typing ...
222
13,424
tinygrad
tinygrad/runtime/ops_tinyfs.py
.py
import socket, json, asyncio, threading, math from contextlib import asynccontextmanager from tinygrad.device import Compiled, Allocator from tinygrad.helpers import DEBUG, getenv, CHUNK_SIZE TINYFS_ENDPOINT = getenv("TINYFS_ENDPOINT", "localhost:6767") TINYFS_TIMEOUT = getenv("TINYFS_TIMEOUT", 60) class TinyFSDevice...
129
4,866
tinygrad
tinygrad/runtime/ops_amd.py
.py
from __future__ import annotations from typing import cast import os, ctypes, struct, hashlib, functools, importlib, mmap, errno, array, contextlib, sys, weakref, itertools, collections, atexit assert sys.platform != 'win32' from dataclasses import dataclass from tinygrad.runtime.support.hcq import HCQCompiled, HCQAllo...
1,104
69,431
tinygrad
tinygrad/runtime/ops_npy.py
.py
import numpy as np from tinygrad.helpers import flat_mv from tinygrad.device import Compiled, Allocator class NpyAllocator(Allocator['NpyDevice']): def _alloc(self, size:int, options=None) -> np.ndarray: return np.empty(size, dtype=np.uint8) def _as_buffer(self, src:np.ndarray) -> memoryview: return flat_mv(np.req...
12
557
tinygrad
tinygrad/runtime/ops_metal.py
.py
import subprocess, pathlib, struct, ctypes, tempfile, functools, decimal, platform from tinygrad.helpers import prod, to_mv, round_up, cache_dir, PROFILE, ProfileRangeEvent, cpu_profile, unwrap, suppress_finalizing import tinygrad.runtime.support.objc as objc from tinygrad.device import Compiled, Compiler, CompileError...
193
12,680
tinygrad
tinygrad/runtime/ops_hip.py
.py
import ctypes from tinygrad.helpers import mv_address, getenv, suppress_finalizing from tinygrad.device import Compiled, LRUAllocator, BufferSpec, Program, TinyELF from tinygrad.runtime.autogen import hip from tinygrad.renderer.cstyle import HIPRenderer from tinygrad.runtime.support.c import init_c_var, init_c_struct_t...
71
4,074
tinygrad
tinygrad/runtime/ops_cuda.py
.py
from __future__ import annotations import ctypes from tinygrad.helpers import DEBUG, DEV, getenv, mv_address, suppress_finalizing from tinygrad.device import Compiled, BufferSpec, LRUAllocator, Program, TinyELF from tinygrad.renderer.cstyle import CUDARenderer, NVCCRenderer from tinygrad.renderer.ptx import PTXRenderer...
135
7,425
tinygrad
tinygrad/runtime/ops_null.py
.py
import inspect, math from tinygrad.device import Compiled, Allocator, ProfileGraphEntry, ProfileGraphEvent, Program, TinyELF from tinygrad.engine.jit import MultiGraphRunner from tinygrad.renderer import Renderer, cstyle, nir, ptx, llvmir, wgsl from tinygrad.renderer.cstyle import CStyleLanguage from tinygrad.uop.ops i...
58
3,283
tinygrad
tinygrad/runtime/ops_dsp.py
.py
from __future__ import annotations import ctypes, os, mmap, tempfile, pathlib, array, threading, contextlib, sys, subprocess, struct assert sys.platform != 'win32' from tinygrad.device import BufferSpec, Compiled, Allocator, Compiler, Program, TinyELF from tinygrad.dtype import dtypes, AddrSpace from tinygrad.uop.ops i...
298
18,227
tinygrad
tinygrad/runtime/ops_python.py
.py
# pylint: disable=cell-var-from-loop # a python uops emulator # works to test the tensor cores, and all the uops in general # this is the (living) definition of uops from typing import Any, TYPE_CHECKING import pickle, base64, itertools, time, sys, functools, ctypes from dataclasses import replace from tinygrad.dtype i...
247
14,352
tinygrad
tinygrad/runtime/ops_nv.py
.py
from __future__ import annotations import os, ctypes, contextlib, re, functools, mmap, struct, array, sys, weakref assert sys.platform != 'win32' from typing import cast from dataclasses import dataclass from tinygrad.runtime.support.hcq import HCQCompiled, HCQAllocator, HCQBuffer, HWQueue, CLikeArgsState, HCQProgram, ...
849
55,250
tinygrad
tinygrad/runtime/ops_cpu.py
.py
from __future__ import annotations import platform, sys, os, ctypes, functools, mmap, threading, array, struct, time from dataclasses import dataclass, replace from typing import cast, Callable from tinygrad.helpers import to_mv, from_mv, OSX, WIN, Context, mv_address, suppress_finalizing, unwrap, data64_le, to_tuple f...
235
15,060
tinygrad
tinygrad/runtime/ops_cl.py
.py
from __future__ import annotations from typing import cast import ctypes, hashlib from tinygrad.runtime.autogen import opencl as cl from tinygrad.runtime.support import c from tinygrad.helpers import to_char_p_p, from_mv, OSX, DEBUG, mv_address, suppress_finalizing, unwrap, round_up, is_image_shape from tinygrad.render...
131
9,055
tinygrad
tinygrad/runtime/autogen/nvrtc.py
.py
# mypy: disable-error-code="empty-body" from __future__ import annotations import ctypes from typing import Literal, TypeAlias from tinygrad.runtime.support.c import _IO, _IOW, _IOR, _IOWR from tinygrad.runtime.support import c import sysconfig dll = c.DLL('nvrtc', 'nvrtc', [f'/{pre}/cuda/targets/{tgt}/lib' for pre in ...
55
5,311
tinygrad
tinygrad/runtime/autogen/avcodec.py
.py
# mypy: disable-error-code="empty-body" from __future__ import annotations import ctypes from typing import Literal, TypeAlias from tinygrad.runtime.support.c import _IO, _IOW, _IOR, _IOWR from tinygrad.runtime.support import c enum_HEVCNALUnitType: dict[int, str] = {(HEVC_NAL_TRAIL_N:=0): 'HEVC_NAL_TRAIL_N', (HEVC_NAL...
468
41,263
tinygrad
tinygrad/runtime/autogen/llvm_qcom.py
.py
# mypy: disable-error-code="empty-body" from __future__ import annotations import ctypes from typing import Literal, TypeAlias from tinygrad.runtime.support.c import _IO, _IOW, _IOR, _IOWR from tinygrad.runtime.support import c dll = c.DLL('llvm_qcom', 'llvm-qcom') cl_llvm_instance: TypeAlias = ctypes.c_void_p @dll.bin...
104
5,473
tinygrad
tinygrad/runtime/autogen/rocprof.py
.py
# mypy: disable-error-code="empty-body" from __future__ import annotations import ctypes from typing import Literal, TypeAlias from tinygrad.runtime.support.c import _IO, _IOW, _IOR, _IOWR from tinygrad.runtime.support import c dll = c.DLL('rocprof', ['rocprof-trace-decoder', p:='/usr/local/lib/rocprof-trace-decoder.so...
171
15,935