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
test/testextra/test_hevc.py
.py
import unittest from tinygrad import Tensor, Device, Variable, dtypes from tinygrad.helpers import DEV, fetch, round_up from tinygrad.engine.realize import compile_linear from tinygrad.uop.ops import Ops from extra.hevc.hevc import parse_hevc_file_headers, nv_gpu from extra.hevc.decode import hevc_decode class TestHe...
107
5,509
tinygrad
test/testextra/test_tk.py
.py
import unittest, math, time from tinygrad import Tensor, Device, dtypes, Context, GlobalCounters from tinygrad.uop.ops import UOp, Ops from tinygrad.engine.realize import run_linear from tinygrad.engine.jit import TinyJit import numpy as np from extra.thunder.tiny.tk import WARP_THREADS from extra.thunder.tiny.tk.ker...
989
35,085
tinygrad
test/testextra/test_export_model.py
.py
import unittest from extra.export_model import export_model, EXPORT_SUPPORTED_DEVICE from tinygrad.tensor import Tensor from tinygrad.device import Device from tinygrad.nn import Linear from tinygrad.nn.state import get_state_dict from tinygrad import dtypes import json class MockMultiInputModel: def forward(self, x...
83
4,241
tinygrad
test/testextra/test_lr_scheduler.py
.py
import numpy as np import torch import unittest from tinygrad.tensor import Tensor from tinygrad.nn.state import get_parameters from tinygrad.nn.optim import Adam, SGD from tinygrad.helpers import DEBUG, Context from extra.lr_scheduler import MultiStepLR, ReduceLROnPlateau, CosineAnnealingLR, OneCycleLR from extra.trai...
122
5,920
tinygrad
test/device/test_validate_with_cpu.py
.py
import unittest from tinygrad import Tensor, Context, Variable, Device from test.helpers import needs_second_gpu class TestValidateWithCPU(unittest.TestCase): def setUp(self): self.ctx = Context(VALIDATE_WITH_CPU=1) self.ctx.__enter__() def tearDown(self): self.ctx.__exit__(None, None, None) def test_ad...
41
1,558
tinygrad
test/device/test_qcom.py
.py
import ctypes, platform, unittest from tinygrad import Device from tinygrad.renderer.cstyle import ClangRenderer class TestQCOM(unittest.TestCase): # although part of the QCOM runtime, this tests flushing the CPU's dcache @unittest.skipUnless(isinstance(Device["CPU"].renderer, ClangRenderer) and platform.machine()...
16
642
tinygrad
test/device/test_amd_llvm.py
.py
import unittest from tinygrad import Device from tinygrad.device import CompileError if Device.DEFAULT == "AMD": # NOTE: if you don't gate this, LVP fails on Mac from tinygrad.runtime.support.compiler_llvm import AMDLLVMCompiler @unittest.skipUnless(Device.DEFAULT == "AMD", "Runs only on AMD") class TestAMDLLVM(un...
43
1,609
tinygrad
test/device/test_hcq2.py
.py
import unittest, numpy as np from unittest.mock import patch from tinygrad import Device, Tensor from tinygrad.helpers import getenv from tinygrad.runtime.support.hcq2 import HCQ_DEVS, all_devices_in @unittest.skipUnless(getenv("HCQ2") and all_devices_in(Device.DEFAULT, HCQ_DEVS), "hcq2 device required") class TestHCQ...
23
1,133
tinygrad
test/device/test_metal.py
.py
import unittest from tinygrad.device import CompileError, Device, BufferSpec, TinyELF from tinygrad.helpers import Target if Device.DEFAULT=="METAL": from tinygrad.runtime.ops_metal import MetalDevice, MetalCompiler @unittest.skipIf(Device.DEFAULT!="METAL", "Metal support required") class TestMetal(unittest.TestCase)...
63
2,322
tinygrad
test/device/test_ocl.py
.py
import unittest from unittest.mock import patch from tinygrad import Device from tinygrad.device import Buffer, TinyELF from tinygrad.dtype import dtypes from tinygrad.helpers import Target from tinygrad.runtime.ops_cl import CLDevice, CLAllocator, CLCompiler @unittest.skipUnless(Device.DEFAULT == "CL", "Runs only on ...
43
1,882
tinygrad
test/device/test_hcq.py
.py
import unittest, ctypes, struct, os, random, numpy as np, time from tinygrad import Device, Tensor, dtypes from tinygrad.helpers import mv_address, DEBUG, DEV from test.helpers import slow, replace_opts from tinygrad.device import Buffer, BufferSpec from tinygrad.runtime.support.hcq import HCQCompiled, HCQBuffer from t...
661
31,574
tinygrad
test/null/test_tensor_metadata.py
.py
import unittest from tinygrad import Tensor, dtypes from tinygrad.tensor import _METADATA from tinygrad.engine.realize import capturing from tinygrad.helpers import Context @unittest.skip("tensor metadata is no longer supported") class TestTensorMetadata(unittest.TestCase): def setUp(self) -> None: _METADATA.set...
128
5,038
tinygrad
test/null/test_uop_resolve.py
.py
import unittest from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp, resolve class TestUOpResolve(unittest.TestCase): def test_simple_int(self): u = UOp.const(4, dtypes.int) self.assertEqual(int(u), 4) def test_weak_const(self): self.assertEqual(int(UOp.const(5)), 5) self.assertEqua...
132
3,324
tinygrad
test/null/test_tqdm.py
.py
import time, random, unittest, itertools from unittest.mock import patch from io import StringIO from collections import namedtuple from tqdm import tqdm from tinygrad.helpers import tqdm as tinytqdm, trange import numpy as np def _get_iter_per_second(raw:str) -> float: # raw might have unit scale if raw.endswith(...
333
15,898
tinygrad
test/null/test_symbolic_failures.py
.py
import unittest from tinygrad import Variable from tinygrad.uop.ops import UOp class TestFuzzFailure(unittest.TestCase): def test_fuzz_failure1(self): v1=Variable('v1', 0, 8) v2=Variable('v2', 0, 2) v3=Variable('v3', 0, 1) expr = (((((((((((((((((((((((0//4)%2)//8)+-2)+-4)+-3)+v1)+-4)+v2)+-2)+v3)+v2...
122
5,674
tinygrad
test/null/test_winograd.py
.py
import unittest, sys from tinygrad import Tensor, GlobalCounters, dtypes, Context from tinygrad.helpers import WINO from test.helpers import check_schedule @unittest.skipIf(sys.platform.startswith("win"), "flaky on Windows") class TestWinograd(unittest.TestCase): def setUp(self): self.old = WINO.value WINO.v...
58
2,420
tinygrad
test/null/test_rewrite_bottom_up_gate.py
.py
import unittest from tinygrad.uop.ops import PatternMatcher, UOp, graph_rewrite, Ops, UPat, BottomUpGate def assert_not_reached(): assert False, "This function should not be reached" def gate(): raise BottomUpGate class TestBottomUpGate(unittest.TestCase): def test_basic_bottom_up_gate(self): """Test that Botto...
29
913
tinygrad
test/null/test_indexing.py
.py
# test cases are modified from pytorch test_indexing.py import unittest from tinygrad import Tensor class TestIndexing(unittest.TestCase): def test_single_int(self): v = Tensor.randn(5, 7, 3) self.assertEqual(v[4].shape, (7, 3)) def test_multiple_int(self): v = Tensor.randn(5, 7, 3) self.assertE...
101
3,591
tinygrad
test/null/test_schedule_cache.py
.py
import unittest from tinygrad import Tensor, Variable, Context from tinygrad.helpers import cpu_events from tinygrad.schedule import schedule_cache def schedule_one(): Tensor([1]).schedule_linear() class TestScheduleCache(unittest.TestCase): def test_bound_variable_var_vals(self): v = Variable('pos', 1, 100) ...
42
1,149
tinygrad
test/null/test_dtype.py
.py
import unittest, pickle from tinygrad.tensor import Tensor from tinygrad.dtype import dtypes, DType, to_dtype, Invalid, InvalidType class TestEqStrDType(unittest.TestCase): def test_strs(self): self.assertEqual(str(dtypes.float32), "dtypes.float") class TestToDtype(unittest.TestCase): def test_dtype_to_dtype(...
70
2,936
tinygrad
test/null/test_tensor_uop_mixin.py
.py
import math, unittest from dataclasses import replace from tinygrad import Tensor, dtypes, Context from tinygrad.uop.ops import ParamArg, UOp, UPat, Ops, PatternMatcher, graph_rewrite _strip_unique_pm = PatternMatcher([ (UPat(Ops.BUFFER, name="b"), lambda b: b.replace(arg=replace(b.arg, slot=0)) if isinstance(b.arg,...
545
31,606
tinygrad
test/null/test_uops.py
.py
# uops tests that pass on NULL backend (no copyout needed) import math, unittest import numpy as np from tinygrad.tensor import Tensor from tinygrad.helpers import Timing, Context, cdiv from tinygrad.dtype import dtypes, AddrSpace, ConstFloat, Invalid # noqa: F401 from tinygrad.device import Device from tinygrad.uop.o...
498
25,006
tinygrad
test/null/test_method_cache.py
.py
import unittest from tinygrad import Tensor, Device, Variable from examples.gpt2 import Transformer from tinygrad.nn.state import get_state_dict class TestMethodCache(unittest.TestCase): def setUp(self): self.backup_compiler = Device[Device.DEFAULT].compiler.compile_cached def tearDown(self): Device[Device...
49
1,812
tinygrad
test/null/test_tensor.py
.py
# tensor tests that pass on NULL backend (no copyout needed) import numpy as np import unittest from tinygrad import Tensor, Device, dtypes from tinygrad.uop.ops import Ops, UOp from tinygrad.renderer.ptx import PTXRenderer from tinygrad.renderer.nir import NIRRenderer from tinygrad.codegen import to_program from tinyg...
213
8,295
tinygrad
test/null/test_const_folding.py
.py
import unittest, itertools, math from tinygrad import Tensor, dtypes, Context from tinygrad.dtype import DType, ConstType from tinygrad.uop.ops import Ops, UOp from test.helpers import full_rewrite import numpy as np def _check_ast_count(desired_count:int, t:Tensor): # NOTE: this has side effect because everything c...
176
7,856
tinygrad
test/null/test_rearrange_einops.py
.py
# modified from # https://github.com/arogozhnikov/einops/blob/master/tests/test_examples.py # https://github.com/arogozhnikov/einops/blob/master/tests/test_ops.py # https://github.com/arogozhnikov/einops/blob/master/tests/test_parsing.py import numpy as np import unittest from tinygrad import Tensor class test_rearr...
172
6,241
tinygrad
test/null/test_tensor_io.py
.py
import unittest from tinygrad import Tensor, dtypes from tinygrad.nn.state import TensorIO class TestTensorIO(unittest.TestCase): def test_create(self): with self.assertRaises(ValueError): TensorIO(Tensor(b"Hello World").reshape(1, -1)) with self.assertRaises(ValueError): TensorIO(Tensor([], dtyp...
25
790
tinygrad
test/null/test_microbenchmarks.py
.py
import unittest, time from tinygrad import Tensor, UOp, getenv from tinygrad.helpers import Profiling PYPROFILE = getenv("PYPROFILE") class TestBench(unittest.TestCase): @staticmethod def setUpClass(): # no fixed cost Tensor.empty(10,10) Tensor.randn(10,10) def start_time(self): self.st = time.perf_...
101
2,701
tinygrad
test/null/test_attention.py
.py
import unittest from tinygrad import Tensor, dtypes, TinyJit, UOp from tinygrad.llm.model import apply_rope as apply_rope_new, precompute_freqs_cis from test.helpers import assert_jit_cache_len, check_schedule def apply_rope(x:Tensor, start_pos:int): B, H, T, Hd = x.shape precompute_freqs_cis.cache_clear() freqs...
36
1,421
tinygrad
test/null/test_transcendental_helpers.py
.py
import unittest, math import numpy as np from tinygrad import dtypes from tinygrad.uop.ops import UOp from tinygrad.codegen.decomp.transcendental import payne_hanek_reduction, cody_waite_reduction, frexp, rintk, pow2if from test.helpers import eval_uop class TestTranscendentalFunctions(unittest.TestCase): def test_p...
75
3,841
tinygrad
test/null/test_process_replay.py
.py
import unittest from tinygrad import Tensor, Device, Context from tinygrad.codegen import do_to_program from tinygrad.codegen.opt import Opt, OptOps from test.external.process_replay.process_replay import replay_to_program from test.helpers import replace_opts N = 16 class TestProcessReplay(unittest.TestCase): @clas...
45
1,642
tinygrad
test/null/test_llm_tokenizer.py
.py
import unittest, base64, functools, re, sys, time, unicodedata from tinygrad.llm.cli import SimpleTokenizer, FallbackTemplate from tinygrad.helpers import fetch @unittest.skipIf(sys.platform == 'win32', "fetch race condition on Windows") class TestLLMTokenizer(unittest.TestCase): @functools.cached_property def lla...
109
6,304
tinygrad
test/null/test_schedule.py
.py
# schedule tests that pass on NULL backend (no copyout needed) import gc, unittest, time from typing import cast from tinygrad import nn, dtypes, Device, Tensor, getenv from tinygrad.uop.ops import UOp, Ops, GroupOp, UPat, KernelInfo, AxisType from tinygrad.helpers import GlobalCounters, Context from tinygrad.engine.re...
2,063
72,682
tinygrad
test/null/test_tensor_uop_representation.py
.py
import unittest from tinygrad import Tensor from tinygrad.uop.ops import UPat, Ops, UOp # NOTE: unlike before base for a realized tensor is always a BUFFER realized_pattern = UPat(Ops.BUFFER) def is_pattern_uop(u:UOp, pat:UPat): assert pat.match(u, {}), f"{u}\nis not\n{pat}" def is_pattern(ten:Tensor, pat:UPat): is_pa...
61
1,795
tinygrad
test/null/test_uops_stats.py
.py
import unittest from tinygrad import Tensor from tinygrad.helpers import GlobalCounters from tinygrad.engine.realize import compile_linear, estimate_uop from tinygrad.codegen import to_program from tinygrad.renderer import Estimates from tinygrad.uop.ops import Ops, UOp from tinygrad.dtype import dtypes from tinygrad.c...
258
10,260
tinygrad
test/null/test_uop_symbolic.py
.py
#!/usr/bin/env python import unittest, pickle, functools, math import z3 from tinygrad.dtype import dtypes, ConstType, DType, Invalid from tinygrad.uop.ops import UOp, Ops, graph_rewrite, sym_infer from tinygrad.uop.spec import spec_shared, type_verify from tinygrad.uop.symbolic import sym, commutative, pm_simplify_va...
1,488
69,251
tinygrad
test/null/test_multitensor.py
.py
import gc, unittest from tinygrad import Tensor, UOp, GlobalCounters, dtypes from tinygrad.engine.jit import TinyJit from tinygrad.helpers import Context class TestMultiRamUsage(unittest.TestCase): def setUp(self): gc.collect() self.baseline = GlobalCounters.mem_used self.baseline_per_device = dict(Globa...
228
8,663
tinygrad
test/null/test_uop_repr.py
.py
import unittest from tinygrad import UOp class TestUOpRepr(unittest.TestCase): def test_simple_const(self): a = UOp.const(42) self.assertEqual(repr(a), "UOp(Ops.CONST, dtypes.weakint, arg=42, src=())") def test_different_consts(self): a, b = UOp.const(42), UOp.const(3) expected = ( "UOp(Ops.A...
39
1,342
tinygrad
test/null/test_gpudims.py
.py
import unittest, math import z3 from tinygrad.codegen.gpudims import get_grouped_dims, add_gpudims from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType from tinygrad.uop.validate import uops_to_z3 from tinygrad.dtype import dtypes from tinygrad.renderer import Renderer from tinygrad.helpers import flatten, dedup...
122
6,780
tinygrad
test/null/test_pattern_matcher.py
.py
import unittest, itertools from tinygrad.dtype import dtypes from tinygrad.uop.ops import Ops, UOp, GroupOp # noqa: F401 from tinygrad.uop.ops import PatternMatcher, UPat class TestPatternMatcher(unittest.TestCase): def test_simple_match(self): matcher = PatternMatcher([(UPat(Ops.CONST, name="x", dtype=dtypes.we...
217
8,682
tinygrad
test/null/test_viz.py
.py
import unittest, decimal, sys, json, contextlib, tempfile, pickle, io, math from pathlib import Path from dataclasses import dataclass from typing import Generator from tinygrad.uop.ops import UOp, UPat, Ops, PatternMatcher, TrackedPatternMatcher, graph_rewrite, rewrite_group from tinygrad.uop.symbolic import sym from...
1,122
48,443
tinygrad
test/null/test_linearizer_failures.py
.py
# ruff: noqa: E501 import unittest from tinygrad.uop.ops import UOp, Ops, AxisType, KernelInfo from tinygrad.dtype import dtypes from tinygrad.device import Device from tinygrad.codegen import to_program class TestLinearizerFailures(unittest.TestCase): def test_fail_1(self): c0 = UOp.param(0, dtypes.float, (64,)...
26
1,138
tinygrad
test/null/test_elf.py
.py
import unittest, subprocess, platform from tinygrad.runtime.support.compiler_cpu import ClangCompiler from tinygrad.runtime.support.elf import elf_loader class TestElfLoader(unittest.TestCase): def test_load_clang_jit_strtab(self): src = ''' int something; // will be a load from a relocation (needed for .r...
39
1,748
tinygrad
test/null/test_simplify_valid_idx.py
.py
import unittest, itertools from tinygrad.codegen.late.coalesce import indexing_simplify from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp, Ops, graph_rewrite from tinygrad.uop.weak import pm_lower_index_dtype from tinygrad.uop.symbolic import simplify_valid, sym, pm_move_where_on_load from tinygrad.he...
597
24,540
tinygrad
test/null/test_symbolic_tensor.py
.py
import unittest from tinygrad import Variable from tinygrad.tensor import Tensor from tinygrad.uop.ops import _broadcast_shape class TestBroadcastShape(unittest.TestCase): def test_symbolic(self): v = Variable("v", 1, 10) self.assertEqual(_broadcast_shape((v,), (1,)), (v,)) self.assertEqual(_broadcast_sh...
130
4,657
tinygrad
test/null/test_gradient.py
.py
from typing import Callable import unittest, math import torch from tinygrad import Tensor from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp from tinygrad.mixin.gradient import compute_gradient class TestGradient(unittest.TestCase): def _cmp_nan_okay(self, x, y): if math.isnan(x) and math.isnan(...
84
3,471
tinygrad
test/null/test_hcq_iface.py
.py
import unittest, array, time from tinygrad.helpers import mv_address from tinygrad.runtime.support.hcq import MMIOInterface from tinygrad.runtime.support.usb import USBMMIOInterface from test.mockgpu.usb import MockUSB class TestHCQIface(unittest.TestCase): def setUp(self): self.size = 4 << 10 self.buffer = ...
106
3,584
tinygrad
test/null/test_resnet.py
.py
import unittest from extra.models import resnet class TestResnet(unittest.TestCase): def test_model_load(self): model = resnet.ResNet18() model.load_from_pretrained() model = resnet.ResNeXt50_32X4D() model.load_from_pretrained() def test_model_load_no_fc_layer(self): model = resnet.ResNet18(n...
21
503
tinygrad
test/null/test_memory_planner.py
.py
import unittest from tinygrad import dtypes from tinygrad.uop.ops import UOp, Ops from tinygrad.schedule.memory import memory_plan_rewrite global_map = {} held_bufs: set[UOp] = set() def b(i, base=None, offset=0, pin=False, size=16): global global_map if i in global_map: return global_map[i] if base is not None:...
257
8,247
tinygrad
test/null/test_validate_oob.py
.py
import unittest from tinygrad import dtypes from tinygrad.dtype import AddrSpace from tinygrad.helpers import Context from tinygrad.uop.ops import Ops, UOp, AxisType from test.helpers import to_uops_list def Variable(name, nmin, nmax): return UOp.variable(name, nmin, nmax, param=True) class TestValidateOOB(unittest.T...
197
8,918
tinygrad
test/null/test_mnist_dataset.py
.py
import unittest from tinygrad.helpers import GlobalCounters from tinygrad.nn.datasets import mnist class TestDataset(unittest.TestCase): def test_dataset_is_realized(self): X_train, _, _, _ = mnist() X_train[0].contiguous().realize() GlobalCounters.reset() X_train[0].contiguous().realize() self.a...
15
452
tinygrad
test/null/test_graph_rewrite.py
.py
import unittest, math from tinygrad import dtypes from tinygrad.dtype import AddrSpace from tinygrad.helpers import all_same, Context from tinygrad.uop.ops import GroupOp, UOp, Ops, exec_alu, PatternMatcher, TrackedPatternMatcher, UPat from test.helpers import full_rewrite from hypothesis import given, strategies as st...
532
22,376
tinygrad
test/null/test_uop_vmin_vmax.py
.py
import unittest, math from tinygrad.uop.ops import UOp, Ops from tinygrad.dtype import dtypes, Invalid, truncate class TestVminVmaxProperties(unittest.TestCase): def test_vmin_vmax_constant(self): # vmin and vmax for a constant uop = UOp.const(42) self.assertEqual(uop.vmin, 42) self.assertEqual(uop.v...
437
15,365
tinygrad
test/null/test_autogen.py
.py
import ctypes, struct, subprocess, tempfile, unittest from tinygrad.helpers import OSX, WIN from tinygrad.runtime.support.c import DLL, record, Field from tinygrad.runtime.support import c from tinygrad.runtime.support.autogen import gen @unittest.skipIf(WIN, "doesn't compile on windows") class TestC(unittest.TestCase...
536
16,083
tinygrad
test/null/test_compile_failures.py
.py
import unittest, io from contextlib import redirect_stdout from tinygrad import Tensor, dtypes, Device from tinygrad.helpers import OSX from tinygrad.engine.realize import compile_linear from tinygrad.codegen import to_program class TestCompileFailures(unittest.TestCase): def compile(self, out:Tensor): compile_l...
31
1,193
tinygrad
test/null/test_llm_server.py
.py
import unittest, threading, time, json from unittest.mock import Mock, patch class TestLLMServer(unittest.TestCase): """Integration tests using the real OpenAI client.""" @classmethod def setUpClass(cls): cls.mock_tok = Mock() cls.mock_tok.encode = Mock(return_value=[200, 201, 202]) cls.mock_tok.dec...
291
13,337
tinygrad
test/null/test_helpers.py
.py
import ctypes, gzip, unittest, timeit, pickle from tinygrad import Variable from tinygrad.helpers import Context, ContextVar, argfix, colored, word_wrap, mv_address, count, all_same from tinygrad.tensor import is_numpy_ndarray from tinygrad.helpers import merge_dicts, strip_parens, prod, round_up, fetch, fully_flatten,...
414
16,943
tinygrad
test/null/test_linearizer_rewrite.py
.py
import unittest from tinygrad import Tensor, Context, Device from tinygrad.codegen import to_program from tinygrad.codegen.opt import Opt, OptOps from tinygrad.uop.ops import KernelInfo class TestLinearizerRewrite(unittest.TestCase): def test_reduction(self): t = Tensor.ones((64,64), device="NULL").contiguous()....
46
1,781
tinygrad
test/null/test_gc.py
.py
#!/usr/bin/env python import gc, inspect import unittest import numpy as np from tinygrad.device import Buffer from tinygrad.engine.realize import run_linear from tinygrad.uop.ops import UOp from tinygrad.tensor import Tensor def _allocations_of_type(t): ret = 0 for x in gc.get_objects(): try: if isinsta...
121
3,659
tinygrad
test/null/test_uop_graph.py
.py
import unittest, pytest from tinygrad import dtypes, Variable, Device from tinygrad.dtype import AddrSpace from tinygrad.helpers import DEBUG, Context from tinygrad.uop.ops import Ops, UOp, UPat, PatternMatcher, graph_rewrite, GroupOp, AxisType, broadcast_axes, KernelInfo from tinygrad.uop.symbolic import sym from test...
741
28,003
tinygrad
test/null/test_dtype_spec.py
.py
import unittest, math, struct, operator from tinygrad import Tensor, Device from tinygrad.dtype import DTYPES_DICT, dtypes, Invalid, truncate, float_to_fp16, float_to_bf16, _to_np_dtype, least_upper_dtype, least_upper_float from tinygrad.helpers import getenv, Context from hypothesis import given, settings, strategies...
452
24,448
tinygrad
test/null/test_disk_cache.py
.py
import unittest import pickle from tinygrad.helpers import diskcache_get, diskcache_put, diskcache, diskcache_clear def remote_get(table,q,k): q.put(diskcache_get(table, k)) def remote_put(table,k,v): diskcache_put(table, k, v) class DiskCache(unittest.TestCase): def test_putget(self): table = "test_putget" ...
109
3,607
tinygrad
test/null/test_real_world.py
.py
import unittest, time, gc import numpy as np from tinygrad.nn import optim from tinygrad.nn.state import get_parameters from tinygrad.engine.jit import TinyJit from tinygrad import Tensor, Device, GlobalCounters, dtypes, Variable from tinygrad.helpers import Context from test.helpers import slow, jit_cache_count, Kerne...
187
8,194
tinygrad
test/null/test_upat_compile.py
.py
import unittest from tinygrad.helpers import DEBUG, Context from tinygrad.dtype import dtypes from tinygrad.uop.ops import UPat, rewrite_group, GroupOp, Ops from tinygrad.uop.upat import _get_code, upat_compile import dis @rewrite_group() def do_compile(up): print("\n***** COMPILE", up) match_code = _get_code(up, ...
55
1,487
tinygrad
test/null/test_device.py
.py
#!/usr/bin/env python import unittest, os, subprocess from unittest.mock import patch from tinygrad import Tensor from tinygrad.device import Device, Compiler, enumerate_devices_str from tinygrad.helpers import diskcache_get, diskcache_put, getenv, Context, Target, WIN, OSX, DEV from tinygrad.runtime.support.c import D...
197
10,608
tinygrad
test/unit/test_system_pci_scan_bus.py
.py
import sys import pytest @pytest.mark.skipif(sys.platform != "linux", reason="uses linux sysfs layout") def test_pci_scan_bus_filters_vendor(monkeypatch): import tinygrad.runtime.support.system as system fake = { "/sys/bus/pci/devices/0000:00:01.0/vendor": "0x1234", "/sys/bus/pci/devices/0000:00:01.0/devi...
29
907
tinygrad
test/unit/test_dtype_weak.py
.py
import tempfile, unittest, math from tinygrad import Tensor, dtypes, TinyJit from tinygrad.helpers import Context from tinygrad.dtype import least_upper_float from tinygrad.uop.ops import UOp, Ops, dtype_from_uop, graph_rewrite from tinygrad.uop.weak import pm_lower_index_dtype, pm_commit_weak from tinygrad.uop.symbol...
293
17,320
tinygrad
test/unit/test_winograd.py
.py
import unittest, sys import numpy as np from tinygrad import Tensor, GlobalCounters, Context, nn from tinygrad.helpers import WINO @unittest.skipIf(sys.platform.startswith("win"), "flaky on Windows") class TestWinogradClose(unittest.TestCase): def test_close(self): inp = Tensor.rand(1, 16, 16, 16) conv = nn....
39
1,318
tinygrad
test/unit/test_indexing.py
.py
# test cases are modified from pytorch test_indexing.py https://github.com/pytorch/pytorch/blob/597d3fb86a2f3b8d6d8ee067e769624dcca31cdb/test/test_indexing.py import unittest, random, warnings import numpy as np from tinygrad import Tensor, dtypes, Device, TinyJit, Variable from tinygrad.helpers import all_same, prod...
1,394
54,795
tinygrad
test/unit/test_jit_footguns.py
.py
#!/usr/bin/env python """ JIT Footguns: Documenting unexpected behavior changes when using @TinyJit Each test shows behavior that works without JIT but changes with JIT. Comments marked "should be X!" indicate the intuitively expected value. SILENT MISMATCHES (highest priority - wrong results, no error): class_meth...
415
15,813
tinygrad
test/unit/test_schedule_cache.py
.py
import unittest import functools from tinygrad import Tensor, Variable, UOp, function from tinygrad.uop.ops import KernelInfo from tinygrad.schedule import schedule_cache def custom_add_kernel(A:UOp, B:UOp, num:int=0) -> UOp: return A[0].set(B[0] + num).sink(arg=KernelInfo(f"custom_add_{num}")) def custom_add_backw...
99
3,410
tinygrad
test/unit/test_invalid_tensor.py
.py
import unittest from tinygrad import Tensor from tinygrad.device import Buffer from tinygrad.dtype import Invalid, dtypes from tinygrad.engine.realize import run_linear from tinygrad.uop.ops import Ops, UOp class TestInvalidTensor(unittest.TestCase): def _invalid_test_helper(self, out, expected): linear, var_val...
148
6,063
tinygrad
test/unit/test_tinyfs.py
.py
import json, math, os, socketserver, threading, unittest import numpy as np from tinygrad import Tensor, dtypes from tinygrad.helpers import CHUNK_SIZE from tinygrad.nn.state import fs_store, fs_load from extra.tinyfs.fetch_file import hash_file, _python_hash_1mb _chunks: dict[bytes, bytes] = {} class _Handler(socket...
84
3,339
tinygrad
test/unit/test_hcq_graph.py
.py
import unittest from tinygrad import Device, Tensor from tinygrad.engine.jit import TinyJit from tinygrad.uop.ops import UOp, Ops from tinygrad.dtype import dtypes from tinygrad.runtime.graph.hcq import HCQGraph from tinygrad.runtime.support.hcq import HCQCompiled from tinygrad.runtime.support.usb import USBMMIOInterfa...
45
2,103
tinygrad
test/unit/test_rearrange_einops.py
.py
# modified from # https://github.com/arogozhnikov/einops/blob/master/tests/test_examples.py # https://github.com/arogozhnikov/einops/blob/master/tests/test_ops.py # https://github.com/arogozhnikov/einops/blob/master/tests/test_parsing.py import numpy as np import unittest from tinygrad import Tensor class test_rearr...
167
6,444
tinygrad
test/unit/test_tensor_io.py
.py
import unittest from tinygrad import Tensor from tinygrad.nn.state import TensorIO class TestTensorIO(unittest.TestCase): def test_read(self): data = b"Hello World!" fobj = TensorIO(Tensor(data)) self.assertEqual(fobj.read(1), data[:1]) self.assertEqual(fobj.read(5), data[1:6]) self.assertEqual(f...
22
585
tinygrad
test/unit/test_allreduce.py
.py
import unittest from tinygrad import Tensor, UOp, dtypes from tinygrad.helpers import Context from tinygrad.uop.ops import Ops class TestRingAllReduce(unittest.TestCase): def test_schedule_ring(self): with Context(RING=2): N = 4 ds = tuple(f"CPU:{i}" for i in range(N)) t = Tensor.empty(N, N*100...
86
3,598
tinygrad
test/unit/test_randomness.py
.py
import unittest, math, torch import numpy as np from functools import partial from tinygrad import nn, dtypes, Tensor, Device, TinyJit, Variable from tinygrad.helpers import OSX # https://gist.github.com/devries/11405101 def ksprob(a): fac, total, termbf = 2.0, 0.0, 0.0 a2 = -2.0 * a * a for j in range(1, 101): ...
201
10,179
tinygrad
test/unit/test_attention.py
.py
import unittest import numpy as np from tinygrad import Tensor, dtypes from tinygrad.llm.model import ( GatedDeltaNetBlock, SSMConfig, TransformerBlock, TransformerConfig, apply_rope as apply_rope_new, precompute_freqs_cis, pairwise_topk, ) def apply_rope(x:Tensor, start_pos:int): B, H, T, Hd = x.shape precomp...
218
12,497
tinygrad
test/unit/test_assign.py
.py
#!/usr/bin/env python import unittest import numpy as np from tinygrad import dtypes, Tensor, TinyJit, GlobalCounters, Variable from tinygrad.uop.ops import Ops, UOp from tinygrad.helpers import temp, DEV, Context from test.helpers import assert_kernel_count N = 200 # has to be bigger than the cache to fail class Te...
1,084
43,053
tinygrad
test/unit/test_cpu.py
.py
import unittest, io from contextlib import redirect_stdout from tinygrad import Tensor, Device from tinygrad.helpers import Target from tinygrad.renderer.nir import LVPRenderer from tinygrad.renderer.isa.x86 import X86Renderer from tinygrad.codegen import to_program @unittest.skipIf(Device.DEFAULT != "CPU", "only run ...
27
1,168
tinygrad
test/unit/test_call.py
.py
import unittest import numpy as np from tinygrad import Tensor, function from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp, Ops class TestCall(unittest.TestCase): def test_call_plus(self): a = Tensor.randn(10, 10) b = Tensor.randn(10, 10) Tensor.realize(a,b) # we define a plus funct...
374
14,726
tinygrad
test/unit/test_conv.py
.py
import unittest import numpy as np from tinygrad.tensor import Tensor from tinygrad.helpers import Context class TestConv(unittest.TestCase): def test_simple(self): x = Tensor.ones(1,12,16,32).contiguous().realize() w = Tensor.ones(32,12,3,3).contiguous().realize() ret = x.conv2d(w, stride=(2,2), padding...
126
3,742
tinygrad
test/unit/test_realize_is_realize.py
.py
import tempfile, unittest import numpy as np from tinygrad import Tensor, Device, dtypes, Variable class TestRealizeIsRealized(unittest.TestCase): def test_list(self): t = Tensor([1, 2, 3]).realize() assert t.uop.is_realized def test_rand(self): t = Tensor.rand(4, 4).realize() assert t.uop.is_real...
68
1,732
tinygrad
test/unit/test_llm_mla.py
.py
import unittest import numpy as np from tinygrad import Tensor from tinygrad.llm.model import Transformer, TransformerConfig, apply_rope, MLATransformerBlock, precompute_freqs_cis class TestMLA(unittest.TestCase): def _make_config(self, **kwargs): return TransformerConfig(**{ "num_blocks": 1, "dim": 64, "h...
72
3,443
tinygrad
test/unit/test_disk_tensor.py
.py
import os, pathlib, tempfile, unittest import numpy as np from tinygrad import Tensor, Device, dtypes from tinygrad.dtype import DType, DTYPES_DICT from tinygrad.nn.state import safe_load, safe_save, get_state_dict, torch_load from tinygrad.helpers import Timing, fetch, OSX, dedup, Context from test.helpers import slow...
580
26,475
tinygrad
test/unit/test_hashing.py
.py
from typing_extensions import Callable import hashlib, random, unittest from tinygrad import Tensor, Device, dtypes from tinygrad.helpers import DEV from test.helpers import slow from tinygrad.uop.ops import UOp from tinygrad.engine.jit import TinyJit supported_dtypes = Device[Device.DEFAULT].renderer.supported_dtypes...
110
5,338
tinygrad
test/unit/test_gguf.py
.py
import os, struct, unittest, tempfile, pathlib, sys from tinygrad import dtypes, Tensor, fetch, Device from tinygrad.helpers import disable_gc from tinygrad.llm.gguf import _ggml_iq_grid, ggml_data_to_tensor, gguf_load from tinygrad.runtime.autogen import ggml_common as _ggml import numpy as np from gguf import GGUFRea...
261
15,507
tinygrad
test/unit/test_multitensor.py
.py
import unittest, numpy as np from tinygrad import Tensor, Variable, Context, Device, TinyJit, GlobalCounters, dtypes, UOp, nn, getenv from tinygrad.nn.state import get_parameters, get_state_dict from tinygrad.uop.ops import Ops from test.helpers import not_support_multi_device, needs_second_gpu, slow, assert_kernel_cou...
1,001
40,920
tinygrad
test/unit/test_linalg.py
.py
import unittest, functools from tinygrad import Tensor, Context import numpy as np def orthogonality_helper(A:Tensor, tolerance=1e-5): b_shape,m = A.shape[0:-2],A.shape[-2] #outer dimension should be the dim along orthogonality A_identity = (Tensor.eye(m).reshape((1,)*len(b_shape)+(m,m)).expand(b_shape+(m,m))) ...
117
4,757
tinygrad
test/unit/test_callify.py
.py
import unittest from tinygrad import Tensor, dtypes class TestCallify(unittest.TestCase): def test_basic(self): a = Tensor([1.,2,3]) b = Tensor([4.,5,6]) out = a + b out.callify() self.assertListEqual(out.tolist(), [5.0, 7.0, 9.0]) def test_const(self): out = Tensor(2.0) + Tensor(3.0) ...
112
2,758
tinygrad
test/unit/test_masked_tensor.py
.py
import unittest from tinygrad.tensor import Tensor class TestMaskedTensor(unittest.TestCase): def test_mul_masked(self): a = Tensor([1,1,1,1,1]) b = Tensor([1,1]).pad(((0,3),)) c = a*b assert c.shape == a.shape ret = c.data() assert ret.tolist() == [1.0, 1.0, 0.0, 0.0, 0.0] def test_mul_bo...
30
750
tinygrad
test/unit/test_tensor_data.py
.py
import unittest, struct from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp # format types: https://docs.python.org/3/library/struct.html class TestTensorBytes(unittest.TestCase): def test_bytes(self): lst = Tensor(bytes(b"\xaa\xbb\xcc\xdd")) assert lst.tolist() == [170, 187, 204, 221] d...
92
2,831
tinygrad
test/unit/test_shm_tensor.py
.py
import unittest import multiprocessing.shared_memory as shared_memory from tinygrad.helpers import WIN from tinygrad import Tensor, Device import numpy as np class TestRawShmBuffer(unittest.TestCase): @unittest.skipIf(WIN, "only fails on CI windows instance") def test_e2e(self): t = Tensor.randn(2, 2, 2).reali...
41
1,150
tinygrad
test/unit/test_llm_moe.py
.py
import unittest import numpy as np from dataclasses import replace from tinygrad import Tensor from tinygrad.llm.model import TransformerBlock, TransformerConfig def _moe_config(dim=8, hidden=16, n_heads=2, num_experts=4, num_experts_per_tok=2): return TransformerConfig( num_blocks=1, dim=dim, hidden_dim=hidden,...
101
4,898
tinygrad
test/unit/test_function.py
.py
import numpy as np import unittest from tinygrad.function import function from tinygrad import Tensor, GlobalCounters, Device from tinygrad.dtype import Invalid from tinygrad.uop.ops import UOp, Ops, KernelInfo, ProgramInfo from test.helpers import assert_kernel_count class TestFunction(unittest.TestCase): def test_...
655
25,305
tinygrad
test/unit/test_symbolic_tensor.py
.py
import unittest from tinygrad import Variable from tinygrad.tensor import Tensor class TestSymbolicPad(unittest.TestCase): def test_pad(self): v = Variable("v", 1, 100).bind(5) t = Tensor.ones(100)[:v].pad(((4, 0),)) t = t[:9] assert t.tolist() == [0,0,0,0,1,1,1,1,1] if __name__ == '__main__': uni...
14
333
tinygrad
test/unit/test_metal_graph.py
.py
import unittest from tinygrad import Device from tinygrad.uop.ops import Ops, UOp from tinygrad.dtype import dtypes @unittest.skipUnless(Device.DEFAULT == "METAL", "Metal device required to run") class TestMetalGraph(unittest.TestCase): def setUp(self): from tinygrad.runtime.graph.metal import MetalGraph sel...
37
1,401
tinygrad
test/unit/test_gradient.py
.py
import unittest, math import numpy as np from tinygrad import Tensor from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp, KernelInfo, Ops class TestTensorGradient(unittest.TestCase): def test_example(self): x = Tensor.eye(3) y = Tensor([[2.0,0,-2.0]]) z = y.matmul(x).sum() dx, dy = z.g...
215
9,224
tinygrad
test/unit/test_tar.py
.py
import unittest, tarfile, io, os, pathlib, tempfile import numpy as np from tinygrad import Tensor from tinygrad.nn.state import tar_extract class TestTarExtractFile(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() self.test_files = { 'file1.txt': b'Hello, World!', 'file2.b...
142
5,224