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/unit/test_setitem_schedule.py
.py
import unittest from tinygrad import Tensor, dtypes, GlobalCounters from test.helpers import assert_kernel_count class TestSetitemInto(unittest.TestCase): def test_setitem_into_unrealized(self): GlobalCounters.reset() t = Tensor.arange(4, dtype=dtypes.int32).reshape(2, 2) assert_kernel_count(0) t[1] ...
144
4,515
tinygrad
test/unit/test_objc.py
.py
import sys, unittest class TestObjCMetaSpec(unittest.TestCase): @unittest.skipUnless(sys.platform == "darwin", "objc runtime only on macOS") def test_classmethods_are_classmethods(self): from tinygrad.runtime.support.objc import Spec, id_ #_classmethods_ must include classmethod descriptors class ObjC...
18
591
tinygrad
test/unit/test_jit_cases.py
.py
import unittest from tinygrad import TinyJit, Tensor # The JIT functions as a "capturing" JIT. # Whatever kernels ran in the JIT the second run through the function will be the kernels that will run from then on. # Explicit inputs to the function are updated in the JIT graph to the new inputs. # JITs have four tensor...
79
2,647
tinygrad
test/unit/test_getitem_ops.py
.py
import unittest import numpy as np from tinygrad import Tensor, GlobalCounters class TestGetitemOps(unittest.TestCase): def test_two_tensor_indices(self): # linear indexing is O(idx_size), one-hot masks is O(idx_size * src_size) src_np = np.random.rand(10, 100, 200).astype(np.float32) idx1_np, idx2_np = ...
22
1,031
tinygrad
test/unit/test_llm_server.py
.py
import unittest from unittest.mock import patch from tinygrad import Tensor, UOp from tinygrad.schedule import schedule_cache from tinygrad.llm.model import Transformer, TransformerConfig from tinygrad.llm.serve import StreamRouter TEST_CONFIG = TransformerConfig(num_blocks=1, dim=64, hidden_dim=128, n_heads=2, n_kv_h...
216
8,935
tinygrad
test/unit/test_helpers.py
.py
import unittest, gc import numpy as np from tinygrad.helpers import polyN, disable_gc from tinygrad.tensor import Tensor, is_numpy_ndarray class TestPolyN(unittest.TestCase): def test_tensor(self): np.testing.assert_allclose(polyN(Tensor([1.0, 2.0, 3.0, 4.0]), [1.0, -2.0, 1.0]).numpy(), [0.0, 1.0, 4.0, 9.0]) cl...
30
916
tinygrad
test/unit/test_jit.py
.py
import unittest, numpy as np from test.helpers import assert_jit_cache_len from tinygrad import Tensor, TinyJit, Context, UOp, dtypes from tinygrad.engine.jit import JitError def _simple_test(add, extract=lambda x: x, N=10): for _ in range(5): a = Tensor.randn(N, N) b = Tensor.randn(N, N) c = add(a, b) ...
443
14,290
tinygrad
test/unit/test_dtype_spec.py
.py
import unittest, math, subprocess from tinygrad.tensor import Tensor from tinygrad.dtype import dtypes, DType, DTYPES_DICT, strong_dtype from tinygrad.device import Device from tinygrad.helpers import getenv, DEBUG, EMULATED_DTYPES, Context from test.helpers import slow from hypothesis import given, settings, strategie...
250
12,911
tinygrad
test/amd/test_emu2_pcode.py
.py
"""Tests for the pcode parser.""" import unittest from collections import defaultdict from tinygrad.helpers import DEBUG from tinygrad.dtype import dtypes from tinygrad.uop.ops import UOp, Ops from test.mockgpu.amd.emu import parse_pcode from test.mockgpu.amd.pcode import parse_expr from tinygrad.runtime.autogen.amd.rd...
397
16,285
tinygrad
test/amd/test_mockgpu_invalid.py
.py
#!/usr/bin/env python3 """Test that invalid instructions raise exceptions through the mock GPU stack.""" import unittest, subprocess, os, sys, time class TestMockGPUInvalidInstruction(unittest.TestCase): def test_unsupported_instruction_raises(self): """Test that unsupported instructions raise immediately throug...
52
1,967
tinygrad
test/amd/test_sqtt_examples.py
.py
#!/usr/bin/env python3 """Tests for SQTT packet decoding using real captured examples.""" import pickle, unittest, ctypes, threading from pathlib import Path from tinygrad.helpers import DEBUG from tinygrad.runtime.autogen import rocprof from tinygrad.runtime.support.elf import elf_loader from tinygrad.renderer.amd imp...
237
12,897
tinygrad
test/amd/test_dsl2.py
.py
import unittest from tinygrad.renderer.amd.dsl import * from tinygrad.renderer.amd.dsl import VDSTYField from tinygrad.runtime.autogen.amd.rdna3.enum import VOP1Op, VOP2Op from tinygrad.runtime.autogen.amd.rdna3.ins import VOP1 class TestRegisters(unittest.TestCase): def test_vgpr_single(self): self.assertEqual(...
171
5,913
tinygrad
test/amd/test_pdf.py
.py
#!/usr/bin/env python3 """Test PDF pseudocode extraction from generate.py.""" import unittest from tinygrad.renderer.amd.generate import extract_pdf_text, extract_pcode, parse_xml, ARCHS, FIXES EXPECTED_PAGES = {"rdna3": 655, "rdna4": 711, "cdna": 610} class TestPcodePDF(unittest.TestCase): pages: dict enums: dic...
54
2,349
tinygrad
test/amd/test_formats.py
.py
#!/usr/bin/env python3 """Test DS and other compute-relevant instruction formats. Note: Graphics-only formats (EXP, MUBUF, MTBUF, MIMG) are not supported - use GLOBAL/FLAT for memory access in compute. """ import unittest from tinygrad.runtime.autogen.amd.rdna3.ins import * from tinygrad.renderer.amd.dsl import VCC_HI...
230
10,476
tinygrad
test/amd/test_integration.py
.py
#!/usr/bin/env python3 """Integration test: round-trip RDNA3 assembly through LLVM toolchain.""" import unittest from tinygrad.runtime.autogen.amd.rdna3.ins import * from test.amd.helpers import llvm_assemble, llvm_disasm def waitcnt(vmcnt: int = 0x3f, expcnt: int = 0x7, lgkmcnt: int = 0x3f) -> int: return (expcnt &...
118
5,767
tinygrad
test/amd/test_roundtrip.py
.py
#!/usr/bin/env python3 """Roundtrip tests: generate tinygrad kernels, decode instructions, re-encode, verify match.""" import unittest, io, sys, re from dataclasses import dataclass from tinygrad import Device from tinygrad.renderer.amd import detect_format from test.amd.helpers import llvm_assemble, llvm_disasm, get_t...
281
13,024
tinygrad
test/amd/test_sqtt_encoder.py
.py
#!/usr/bin/env python3 """Tests for SQTT encoder: verifies the emulator produces correct SQTT traces for known kernels. Run with: DEV=MOCK+AMD python -m pytest test/amd/test_sqtt_encoder.py -v """ import ctypes, unittest from tinygrad.helpers import Context from tinygrad.renderer.amd.sqtt import decode, LAYOUT_HEADER,...
109
4,959
tinygrad
test/amd/test_rdna3_asm.py
.py
#!/usr/bin/env python3 import unittest from tinygrad.runtime.autogen.amd.rdna3.ins import * from test.amd.helpers import llvm_assemble from test.amd.disasm import disasm def _asm(asm: str) -> bytes: return llvm_assemble([asm], 'gfx1100', '+real-true16,+wavefrontsize32')[0] class TestRDNA3Asm(unittest.TestCase): def...
67
2,855
tinygrad
test/amd/disasm.py
.py
# RDNA3/RDNA4/CDNA disassembler from __future__ import annotations import re from typing import Callable from test.amd.helpers import decode_dpp16 from tinygrad.renderer.amd.dsl import Inst, Reg # Special register mappings for disassembly SPECIAL_GPRS = {106: 'vcc_lo', 107: 'vcc_hi', 124: 'null', 125: 'm0', 126: 'exec...
946
58,736
tinygrad
test/amd/test_llvm.py
.py
#!/usr/bin/env python3 """Test AMD assembler/disassembler against LLVM test vectors. Only compute-relevant instruction formats are tested. Graphics-only formats not supported: - MUBUF/MTBUF: buffer instructions with resource descriptors (use GLOBAL/FLAT instead) - MIMG: image/texture instructions - EXP/VEXPORT: ...
157
9,007
tinygrad
test/amd/test_sqttmap.py
.py
# test to compare every packet with the rocprof decoder import unittest, pickle, functools, json from typing import Iterator from pathlib import Path from tinygrad.helpers import DEBUG, getenv, temp, ansistrip, Context from tinygrad.renderer.amd.sqtt import print_packets, map_insts from tinygrad.runtime.autogen.amd.rdn...
176
9,014
tinygrad
test/amd/test_sqtt_profiler.py
.py
import unittest, contextlib from tinygrad import Device, Tensor, Context, TinyJit from tinygrad.device import Compiled, ProfileProgramEvent, ProfileDeviceEvent from tinygrad.engine.realize import run_linear from tinygrad.codegen import to_program from tinygrad.viz.serve import load_amd_counters, VizData @contextlib.co...
100
3,770
tinygrad
test/amd/helpers.py
.py
"""Shared test helpers for AMD tests.""" import ctypes from tinygrad.helpers import unwrap from tinygrad.runtime.autogen import llvm from tinygrad.runtime.support.elf import elf_loader ARCH_TO_TARGET:dict[str, list[str]] = { "rdna3":["gfx1100", "gfx1151"], "rdna4":["gfx1200", "gfx1201"], "cdna":["gfx950", "gfx94...
133
6,508
tinygrad
test/amd/test_asm_kernel.py
.py
import unittest import functools import numpy as np from tinygrad import Tensor, Device, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo from tinygrad.engine.realize import run_linear, estimate_uop, compile_linear from tinygrad.renderer import Estimates from tinygrad.dtype import AddrSpace from tinygrad.helper...
213
9,314
tinygrad
test/amd/test_handwritten.py
.py
# do not change these tests. we need to fix bugs to make them pass # the Inst constructor should be looking at the types of the fields to correctly set the value import unittest, struct from tinygrad.runtime.autogen.amd.rdna3.ins import * from tinygrad.renderer.amd.dsl import Inst from test.amd.test_roundtrip import c...
198
6,731
tinygrad
test/amd/hw/test_rdna4_permlane_var.py
.py
"""RDNA4 V_PERMLANE16_VAR_B32 / V_PERMLANEX16_VAR_B32 coverage. Exercises the generated pcode path end-to-end in the emulator and compares against real RDNA4 hardware when USE_HW=1. """ import ctypes, unittest import tinygrad.runtime.autogen.amd.rdna4.ins as r4 from tinygrad.helpers import Target, flat_mv from tinygra...
129
4,317
tinygrad
test/amd/hw/test_sop.py
.py
"""Tests for SOP instructions - scalar operations. Includes: s_add_u32, s_mov_b32, s_and_b32, s_or_b32, s_quadmask_b32, s_wqm_b32, s_cbranch_vccnz, s_cbranch_vccz """ import unittest from test.amd.hw.helpers import * class TestBasicScalar(unittest.TestCase): """Tests for basic scalar operations.""" def...
1,008
36,499
tinygrad
test/amd/hw/test_dpp.py
.py
"""Tests for DPP16 source swizzles. These instructions trap in the default wave32 hw helper, so this file uses a minimal wave64 lane-store harness and compares emulator vs hardware directly when USE_HW=1. """ import ctypes, unittest from tinygrad.runtime.autogen.amd.rdna3.ins import * from tinygrad.helpers import Targ...
187
6,286
tinygrad
test/amd/hw/test_smem.py
.py
"""Tests for SMEM instructions - scalar memory operations. Includes: s_load_b32, s_load_b64, s_load_b128, s_load_b256, s_load_b512 Tests both immediate and register offset addressing modes. """ import unittest from test.amd.hw.helpers import * # Use offset into output buffer for test data (output buffer is 2124 bytes...
449
19,638
tinygrad
test/amd/hw/test_cdna_vop3.py
.py
"""CDNA VOP3 instruction coverage. Exercises generated CDNA pcode end-to-end in the emulator and compares against gfx950 hardware when USE_HW=1. """ import ctypes, struct, unittest import tinygrad.runtime.autogen.amd.cdna.ins as cdna from tinygrad.helpers import Target, flat_mv from tinygrad.renderer.amd.dsl import NU...
130
4,476
tinygrad
test/amd/hw/test_vop3p.py
.py
"""Tests for VOP3P instructions - packed 16-bit vector operations. Includes: v_pk_add_f16, v_pk_mul_f16, v_pk_fma_f16, v_pack_b32_f16, v_wmma_*, v_dot2_* """ import unittest from test.amd.hw.helpers import * class TestPackInstructions(unittest.TestCase): """Tests for pack instructions.""" def test_v_pack_b32_f16...
1,037
40,623
tinygrad
test/amd/hw/test_global.py
.py
"""Tests for GLOBAL instructions - global memory operations. Includes: global_load_*, global_store_*, global_atomic_*, global_load_d16_* """ import unittest from test.amd.hw.helpers import * class TestGlobalAtomic(unittest.TestCase): """Tests for GLOBAL atomic instructions.""" def _make_test(self, setup_instrs, ...
680
29,628
tinygrad
test/amd/hw/test_flat.py
.py
"""Tests for FLAT instructions - flat memory operations. Includes: flat_load_*, flat_store_*, flat_atomic_* """ import unittest from test.amd.hw.helpers import * class TestFlatAtomic(unittest.TestCase): """Tests for FLAT atomic instructions.""" def _make_test(self, setup_instrs, atomic_instr, check_fn, test_offs...
364
14,790
tinygrad
test/amd/hw/test_ds.py
.py
"""Tests for DS instructions - data share (LDS) operations. Includes: ds_store_b32, ds_load_b32, ds_store_2addr_*, ds_load_2addr_*, ds_add_*, ds_max_*, ds_min_*, ds_and_*, ds_or_*, ds_xor_*, ds_inc_*, ds_dec_*, ds_cmpstore_*, ds_storexchg_* """ import unittest from test.amd.hw.helpers import * cla...
961
40,526
tinygrad
test/amd/hw/test_vop1.py
.py
"""Tests for VOP1 instructions - single operand vector operations. Includes: v_mov_b32, v_cvt_*, v_sin_f32, v_rcp_f32, v_exp_f32, v_rndne_f32, v_floor_f32, v_trunc_f32, v_fract_f32, v_clz_i32_u32, v_ctz_i32_b32, v_readfirstlane_b32 """ import unittest from test.amd.hw.helpers import * class TestMo...
1,634
53,809
tinygrad
test/amd/hw/test_vopd.py
.py
"""Tests for VOPD instructions - dual-issue vector operations. VOPD executes two operations simultaneously. Key behavior: - Both ops read their sources BEFORE either writes (dual-issue semantics) - This means if X writes to a register that Y reads, Y sees the OLD value - Op X can use ops 0-15 (FMAC, MUL, ADD, MOV, etc...
202
8,915
tinygrad
test/amd/hw/test_vinterp.py
.py
"""Tests for VINTERP instructions.""" import unittest from test.amd.hw.helpers import * class TestVInterp(unittest.TestCase): def test_v_interp_p10_f32(self): instructions = [ v_mov_b32_e32(v[10], v[255]), v_cvt_f32_u32_e32(v[1], v[10]), s_mov_b32(s[0], f2i(100.0)), v_add_f32_e32(v[1], s[...
36
1,359
tinygrad
test/amd/hw/test_scratch.py
.py
"""Tests for SCRATCH instructions - scratch (private) memory operations. Includes: scratch_load_*, scratch_store_* """ import unittest from test.amd.hw.helpers import * class TestScratchStore(unittest.TestCase): """Tests for SCRATCH store instructions.""" def test_scratch_store_b32_basic(self): """SCRATCH_ST...
356
14,754
tinygrad
test/amd/hw/test_vopc.py
.py
"""Tests for VOPC instructions - vector compare operations. Includes: v_cmp_class_f32, v_cmp_class_f16, v_cmp_eq_*, v_cmp_lt_*, v_cmp_gt_* """ import unittest from test.amd.hw.helpers import * VCC = 106 # SGPR index for VCC_LO class TestCmpClass(unittest.TestCase): """Tests for V_CMP_CLASS_F32 float classificatio...
979
38,450
tinygrad
test/amd/hw/helpers.py
.py
"""Test infrastructure for hardware-validated RDNA3 emulator tests. Uses run_asm() with memory output, so tests can run on both emulator and real hardware. Set USE_HW=1 to run on both emulator and hardware, comparing results. """ import ctypes, math, os, struct from tinygrad.runtime.autogen.amd.rdna3.ins import * fro...
287
11,057
tinygrad
test/amd/hw/test_vop2.py
.py
"""Tests for VOP2 instructions - two operand vector operations. Includes: v_add_f32, v_mul_f32, v_and_b32, v_or_b32, v_xor_b32, v_lshrrev_b32, v_lshlrev_b32, v_fmac_f32, v_fmaak_f32, v_fmamk_f32, v_add_nc_u32, v_cndmask_b32, v_add_f16, v_mul_f16 """ import unittest from test.amd.hw.helpers import *...
995
38,088
tinygrad
test/amd/hw/test_cdna_sdwa.py
.py
#!/usr/bin/env python3 import unittest import tinygrad.runtime.autogen.amd.cdna.ins as cdna from test.amd.hw.test_cdna_vop3 import run_cdna class TestCDNASDWA(unittest.TestCase): def test_v_add_co_u32_e32_writes_vcc(self): out = run_cdna([ cdna.s_mov_b32(cdna.s[0], 0xffffffff), cdna.v_mov_b32_e32(cdn...
21
739
tinygrad
test/amd/hw/test_vop3.py
.py
"""Tests for VOP3 instructions - three operand vector operations. Includes: v_fma_f32, v_div_scale_f32, v_div_fmas_f32, v_div_fixup_f32, v_alignbit_b32, v_bfe_i32, v_mad_u64_u32, v_readlane_b32, v_writelane_b32 """ import unittest from test.amd.hw.helpers import * class TestFMA(unittest.TestCase): """Test...
3,657
133,578
tinygrad
test/external/external_test_onnx_ops.py
.py
# inputs, attributes, and outputs for tests are found here: # https://github.com/onnx/onnx/blob/main/docs/Operators.md # https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md from typing import Any import unittest, onnx, tempfile from tinygrad import dtypes, Tensor, Context from tinygrad.nn.onnx ...
623
32,729
tinygrad
test/external/external_test_hive_reset.py
.py
#!/usr/bin/env python3 import subprocess, sys from tinygrad.helpers import getenv LOOPS = getenv("LOOPS", 50) BROKEN = getenv("BROKEN", 0) ONLY_RESET = getenv("ONLY_RESET", 0) BROKEN_KERNEL_SCRIPT = """ from tinygrad.device import Device from tinygrad.runtime.ops_amd import AMDProgram, AMDDevice from tinygrad.runtime...
44
1,585
tinygrad
test/external/external_test_whisper_librispeech.py
.py
import unittest import torch import tqdm import torchaudio import pathlib import jiwer import os import numpy as np from whisper.normalizers import EnglishTextNormalizer from examples.whisper import init_whisper, transcribe_waveform class TestWhisperLibriSpeech(unittest.TestCase): # reference WERs determined by runn...
84
2,726
tinygrad
test/external/external_test_usb_asm24.py
.py
import unittest from tinygrad.helpers import Timing, getenv from tinygrad import Tensor, Device import numpy as np class TestDevCopySpeeds(unittest.TestCase): @classmethod def setUpClass(cls): cls.sz = getenv("SIZE", 2e6) cls.dev = Device["AMD"] if not cls.dev.is_usb(): raise unittest.SkipTest("only te...
39
1,326
tinygrad
test/external/fuzz_kfd.py
.py
#!/usr/bin/env python3 import random from tqdm import trange from typing import List from tinygrad import Device from tinygrad.runtime.ops_amd import AMDDevice, HWQueue if __name__ == "__main__": dev: List[AMDDevice] = [Device[f"KFD:{i}"] for i in range(6)] print(f"got {len(dev)} devices") buffers = [(rd:=rando...
29
859
tinygrad
test/external/external_test_dev_var.py
.py
import subprocess, unittest, os, sys from tinygrad.device import Device class TestTinygradSlow(unittest.TestCase): def test_env_overwrite_default_device(self): subprocess.run([f'DEV={Device.DEFAULT} python3 -c "from tinygrad import Device; assert Device.DEFAULT == \\"{Device.DEFAULT}\\""'], s...
27
1,361
tinygrad
test/external/external_benchmark_op_conv.py
.py
# ruff: noqa: E501 E712 F401 from dataclasses import replace from tinygrad import dtypes, Device from tinygrad.uop.ops import UOp, AxisType, Ops, KernelInfo from tinygrad.codegen.opt import Opt, OptOps # pylint: disable=unused-import from tinygrad.engine.realize import get_runtime from tinygrad.codegen import to_progra...
103
4,598
tinygrad
test/external/external_benchmark_am.py
.py
from tinygrad.helpers import Profiling from tinygrad import Device if __name__ == "__main__": am = Device["AMD"] # kfd is 0.55ms! with Profiling("allocation 127.7mb"): am.allocator.alloc(int(127.7*1024*1024))
10
221
tinygrad
test/external/fuzz_shape_ops.py
.py
from __future__ import annotations import unittest from math import prod from hypothesis import assume, given, settings, strategies as st from hypothesis.extra import numpy as stn import numpy as np import torch from tinygrad import Tensor from tinygrad.helpers import getenv settings.register_profile(__file__, sett...
88
3,005
tinygrad
test/external/external_test_hip_compile.py
.py
import time, unittest from tinygrad.runtime.support.hip_comgr import compile_hip from tinygrad import Tensor from tinygrad.device import Device from tinygrad.schedule import create_schedule from tinygrad.codegen.opt.kernel import Kernel class TestHIPCompileSpeed(unittest.TestCase): @unittest.skipIf(Device.DEFAULT !=...
40
1,649
tinygrad
test/external/external_fuzz_hcq_mp.py
.py
import subprocess import random import time from concurrent.futures import ProcessPoolExecutor, as_completed from tinygrad.helpers import getenv # checks that HCQ drivers can be killed during operation without causing issues def run_test(i, full_run=False, force_ok=False): print(f"\rRunning iteration {i}...", end="...
45
1,527
tinygrad
test/external/external_benchmark_multitensor_allreduce.py
.py
from tinygrad import Tensor, Device, GlobalCounters, TinyJit, dtypes from tinygrad.helpers import getenv, Context, DEBUG def test(devs: list[str], N: int, iters:int = 10, name:str = "allreduce"): @TinyJit def f(t: Tensor) -> Tensor: t.sum(0).realize() secs, gflops, gbs = 0, 0, 0 for i in range(-3, iters): ...
50
1,849
tinygrad
test/external/fuzz_graph.py
.py
import random import numpy as np from tinygrad.device import Buffer, Device from tinygrad.helpers import Context, getenv from tinygrad.dtype import dtypes from tinygrad.tensor import Tensor, _to_np_dtype from tinygrad.engine.realize import BufferXfer, get_runner, ExecItem from tinygrad.uop.ops import UOp, Ops from tiny...
128
4,718
tinygrad
test/external/external_fuzz_sdma_warm_start.py
.py
import subprocess, sys, os, random CHILD_SCRIPT = """ import os, random import numpy as np from tinygrad import Tensor, Device from tinygrad.runtime.ops_amd import AMDDevice dev = Device["AMD"] for i in range({N}): sz = random.randint(1, {MAX_SZ}) data = np.random.randint(0, 256, sz, dtype=np.uint8) t = Tensor(...
56
1,797
tinygrad
test/external/external_test_losses.py
.py
from tinygrad import Tensor from test.external.mlperf_retinanet.focal_loss import sigmoid_focal_loss as ref_sigmoid_focal_loss from test.external.mlperf_unet3d.dice import DiceCELoss from examples.mlperf.losses import dice_ce_loss, sigmoid_focal_loss, l1_loss import numpy as np import torch import unittest class Exte...
40
1,965
tinygrad
test/external/external_multi_gpu.py
.py
#!/usr/bin/env python3 # cd extra/disassemblers/ && git clone --recursive github.com:geohot/cuda_ioctl_sniffer.git # LD_PRELOAD=$PWD/extra/disassemblers/cuda_ioctl_sniffer/out/sniff.so DEV=CL python3 test/external/external_multi_gpu.py import numpy as np from tinygrad.tensor import Tensor from tinygrad.helpers import c...
80
2,559
tinygrad
test/external/fuzz_fast_idiv.py
.py
import random import z3 from tinygrad import dtypes, Device from tinygrad.uop.validate import uops_to_z3, z3_cdiv from tinygrad.uop.ops import UOp from tinygrad.codegen.decomp.op import fast_idiv random.seed(42) powers_of_two = [2**i for i in range(64)] if __name__ == "__main__": for i in range(10_000): if i % 1...
26
897
tinygrad
test/external/external_test_gpu_crash.py
.py
# ruff: noqa: F405 """Tests for GPU crash scenarios using AMD assembly to trigger invalid operations. These tests intentionally cause GPU faults to verify error handling. Run with: DEV=AMD python -m pytest test/external/external_test_gpu_crash.py -v """ import unittest, re, importlib from tinygrad import Device, UOp, ...
129
6,321
tinygrad
test/external/external_benchmark_bert_softmax.py
.py
from tinygrad import Tensor, dtypes, GlobalCounters from tinygrad.dtype import to_dtype from tinygrad.helpers import getenv, Context from test.backend.test_softmax_fusion import single_kernel_softmax Context(DEFAULT_FLOAT=dtypes.float16).__enter__() if __name__ == "__main__": # softmax in bert layers BS = getenv(...
19
572
tinygrad
test/external/external_test_opt.py
.py
#!/usr/bin/env python import gc, unittest import numpy as np import torch from tinygrad import GlobalCounters, Tensor, Device from tinygrad.helpers import getenv, Context from tinygrad.nn.state import get_parameters from tinygrad.engine.realize import capturing, run_linear from tinygrad.tensor import _to_np_dtype cla...
237
9,450
tinygrad
test/external/external_test_onnx_runner.py
.py
import unittest, onnx, tempfile, pathlib import numpy as np from tinygrad import Tensor from tinygrad.uop.ops import Ops from typing import Any from tinygrad.nn.onnx import OnnxRunner, OnnxPBParser, OnnxDataType from hypothesis import given, strategies as st # copied from test_const_folding.py def _check_ast_count(des...
165
7,788
tinygrad
test/external/external_metal_compile_fail.py
.py
# AssertionError: Error Domain=AGXMetalG15X_B0 Code=3 "Compiler encountered an internal error" src = """ #include <metal_stdlib> using namespace metal; kernel void r_64_32_8_16_4_6_6_4(device float* data0, const device float* data1, uint3 gid [[threadgroup_position_in_grid]], uint3 lid...
231
8,432
tinygrad
test/external/external_test_simple_tokenizer.py
.py
import functools, multiprocessing from transformers import AutoTokenizer from datasets import load_dataset from tinygrad.llm.cli import SimpleTokenizer from tinygrad.helpers import tqdm, getenv, partition @functools.cache def get_tokenizers(): print("getting tokenizers") base_tokenizer = AutoTokenizer.from_pretrai...
51
2,144
tinygrad
test/external/external_test_yolov8.py
.py
import numpy as np from examples.yolov8 import YOLOv8, get_variant_multiples, preprocess, label_predictions, postprocess from tinygrad import Tensor import unittest import io, cv2 import onnxruntime as ort import ultralytics from tinygrad.nn.state import safe_load, load_state_dict from tinygrad.helpers import fetch cl...
74
3,852
tinygrad
test/external/external_fuzz_hcq_signals.py
.py
import random from tinygrad import Device from tinygrad.helpers import getenv, DEBUG def main(): seed = getenv("SEED", 1337) n_gpus = getenv("GPUS", 3) iters = getenv("ITERS", 10000000) only_compute = bool(getenv("ONLY_COMPUTE", 0)) print(f"{n_gpus} GPUs for {iters} iterations, {only_compute=}, seed {seed}"...
32
1,200
tinygrad
test/external/external_benchmark_llama_offload.py
.py
from tinygrad import Tensor, dtypes, Device, TinyJit from tinygrad.helpers import getenv, Timing, round_up # llama 70b shapes DIM, HIDDEN, N_HEADS, N_KV_HEADS, HEAD_DIM = 8192, 28672, 64, 8, 128 QKV_OUT = N_HEADS*HEAD_DIM + 2*N_KV_HEADS*HEAD_DIM LAYER_SHAPES = { "wqkv": ((QKV_OUT, DIM), 0), "wo": ((DIM, N_HEADS*HE...
69
2,134
tinygrad
test/external/external_benchmark_disk_raw.py
.py
import pathlib from tinygrad import Tensor, Device, Context from tinygrad.helpers import getenv if __name__ == "__main__": with Context(DEBUG=2): disk_llama = Tensor(pathlib.Path(getenv("TESTFILE", "/raid/weights/LLaMA-3/8B/consolidated.00.pth"))) device_llama = disk_llama.to(Device.DEFAULT).realize()
9
314
tinygrad
test/external/external_benchmark_resnet.py
.py
import functools import time import unittest from tinygrad import Tensor, TinyJit, GlobalCounters, Device from tinygrad.helpers import getenv, Context from tinygrad.nn.optim import SGD from tinygrad.nn.state import get_parameters from tinygrad.engine.realize import run_linear from extra.models import resnet from exam...
128
5,737
tinygrad
test/external/external_test_metrics.py
.py
from tinygrad import Tensor from test.external.mlperf_unet3d.dice import DiceScore from examples.mlperf.metrics import dice_score, log_perplexity import numpy as np import torch import unittest, math class ExternalTestMetrics(unittest.TestCase): def _test_metrics(self, tinygrad_metrics, orig_metrics, pred, label, a...
42
2,322
tinygrad
test/external/external_test_llama3_ff.py
.py
#!/usr/bin/env python3 from tinygrad import Tensor, TinyJit, nn from extra.models.llama import FeedForward if __name__ == "__main__": model = FeedForward(4096, 14336) for x in nn.state.get_parameters(model): x.replace(x.half()).realize() jrun = TinyJit(model) for i in range(5): print(f"*** run {i}") jr...
13
346
tinygrad
test/external/external_test_lm_head.py
.py
from tinygrad import Tensor, nn if __name__ == "__main__": vocab_size = 50257 n_embd = 768 lm_head = nn.Linear(n_embd, vocab_size, bias=False) bs = 4 seq_len = 1024 x = Tensor.rand(bs, seq_len, n_embd) ret = lm_head(x).realize()
11
244
tinygrad
test/external/external_test_speed_theoretical.py
.py
import time, unittest from tinygrad import Tensor, TinyJit, Device, dtypes from tinygrad.helpers import getenv, GlobalCounters SZMAX = getenv("SZMAX", 10) SZMIN = min(SZMAX, getenv("SZMIN", 10)) def _test(tcount, fxn, dtype=dtypes.float): print(f"**** testing {fxn.__name__} {dtype}") allgbs = [] for sz in range(...
49
1,794
tinygrad
test/external/external_benchmark_bert_matmuls.py
.py
from tinygrad import Tensor, dtypes from tinygrad.dtype import to_dtype from tinygrad.helpers import getenv, Context Context(DEFAULT_FLOAT=dtypes.float16).__enter__() if __name__ == "__main__": # matmuls in bert layers BS = getenv("BS", 96//6) acc_dtype = to_dtype(getenv("ACC_DTYPE", "half")) tensors = [ ...
20
852
tinygrad
test/external/fuzz_symbolic_div.py
.py
import random, sys import z3 from tinygrad.uop.ops import UOp, Ops from tinygrad.uop.validate import uops_to_z3 from tinygrad.helpers import DEBUG, colored seed = int(sys.argv[1]) if len(sys.argv) > 1 else random.randint(0, 100) print(f"Seed: {seed}", flush=True) random.seed(seed) def get_random_term(ranges, factors)...
66
2,744
tinygrad
test/external/external_test_image.py
.py
#!/usr/bin/env python import os import unittest import numpy as np if 'IMAGE' not in os.environ: os.environ['IMAGE'] = '2' os.environ['CL'] = '1' os.environ['OPT'] = '2' from tinygrad.tensor import Tensor from tinygrad.nn import Conv2d class TestImage(unittest.TestCase): def test_create_image(self): t = Tensor...
52
1,507
tinygrad
test/external/speed_v_theoretical.py
.py
import unittest from tinygrad import Tensor, TinyJit, Device from tinygrad.helpers import Context, DEBUG, GlobalCounters from tinygrad.nn import Conv2d from tinygrad.nn.state import get_parameters class TestKernelSpeed(unittest.TestCase): def _get_tensor(self, *shape:int): with Context(BEAM=0, DEBUG=0): # ...
101
3,669
tinygrad
test/external/external_llm_eval.py
.py
# eval for OpenAI API server # uses Meta's exact ARC-Challenge prompt template from lm-evaluation-harness llama3 tasks import argparse, re, pyarrow.parquet as pq from openai import OpenAI from tinygrad.helpers import fetch, colored LABEL = ["A", "B", "C", "D"] if __name__ == "__main__": parser = argparse.ArgumentPa...
51
3,030
tinygrad
test/external/external_test_am.py
.py
import unittest from tinygrad.runtime.support.am.amdev import AMMemoryManager, AMPageTableEntry from tinygrad.runtime.support.am.ip import AM_GMC from tinygrad.runtime.support.hcq import MMIOInterface from tinygrad.runtime.support.memory import PageTableTraverseContext, AddrSpace from tinygrad.runtime.autogen.am import...
225
9,603
tinygrad
test/external/external_test_mnist_data_select.py
.py
#!/bin/bash from tinygrad import Tensor from extra.datasets import fetch_mnist if __name__ == "__main__": X_train, Y_train, X_test, Y_test = fetch_mnist(tensors=True) samples = Tensor.randint(512, high=X_train.shape[0]) select = X_train[samples].realize()
9
263
tinygrad
test/external/external_test_mamba.py
.py
import unittest from test.helpers import slow from examples.mamba import Mamba, generate from transformers import AutoTokenizer PROMPT = 'Why is gravity ' TOKENIZER = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b") @slow class TestMamba(unittest.TestCase): def test_mamba_130M(self): OUT_130M = '''Why i...
25
849
tinygrad
test/external/external_test_datasets.py
.py
from extra.datasets.kits19 import iterate, preprocess from examples.mlperf.dataloader import batch_load_unet3d, batch_load_retinanet from test.external.mlperf_retinanet.coco_utils import get_openimages from test.external.mlperf_retinanet.openimages import postprocess_targets from test.external.mlperf_retinanet.presets ...
173
7,730
tinygrad
test/external/external_fuzz_beam_timeout_recovery.py
.py
#!/usr/bin/env python3 """ Stress test for beam timeout + device recovery on AM devices. Usage: DEV=AMD python test/external/external_fuzz_beam_timeout_recovery.py """ from tinygrad import Tensor, Device from tinygrad.helpers import Context from tinygrad.runtime.ops_amd import AMDDevice if __name__ == "__main__": ...
32
1,087
tinygrad
test/external/external_cl_half_max.py
.py
from tinygrad.runtime.ops_cl import CLDevice, CLProgram, compile_cl if __name__ == "__main__": dev = CLDevice() lib = compile_cl(""" #pragma OPENCL EXTENSION cl_khr_fp16 : enable __kernel void test(__global half *out, __global half *a, __global half *b) { int gid = get_global_id(0); out[gid] = max(a[gid], b[gi...
14
369
tinygrad
test/external/external_test_optim.py
.py
#!/usr/bin/env python import unittest import numpy as np import tensorflow as tf from tensorflow.keras.optimizers import Lamb from tensorflow.python.ops import math_ops from extra.lr_scheduler import LRSchedulerGroup from tinygrad.tensor import Tensor from tinygrad.nn.optim import LAMB, LARS, SGD, OptimizerGroup from ...
175
7,370
tinygrad
test/external/external_test_example.py
.py
import unittest, sys from tinygrad import Device from tinygrad.tensor import Tensor from tinygrad.helpers import getenv, OSX def multidevice_test(fxn): exclude_devices = getenv("EXCLUDE_DEVICES", "").split(",") def ret(self): for device in Device._devices: # broken on OSX USB AMD, why? if device in...
75
2,094
tinygrad
test/external/external_benchmark_hip_compile.py
.py
import random, os from tinygrad.helpers import Timing from tinygrad.runtime.ops_hip import compile_hip, HIPDevice from tinygrad.runtime.ops_cl import compile_cl, CLDevice # OMP_NUM_THREADS=1 strace -tt -f -e trace=file python3 test/external/external_benchmark_hip_compile.py # AMD_COMGR_REDIRECT_LOGS=stdout AMD_COMGR_E...
32
1,160
tinygrad
test/external/external_benchmark_pyrender.py
.py
# benchmark speed of pyrender for all created UOps saved with TRACK_MATCH_STATS=2 import functools, pickle from tinygrad.uop.ops import UOp, Ops from tinygrad.helpers import tqdm, temp, time_to_str, cpu_profile BENCHMARK_OPS = {Ops.INDEX, Ops.STAGE} @functools.cache def create_uop(a:int) -> UOp: op, dtype, src, arg...
35
1,181
tinygrad
test/external/external_test_lr_schedule.py
.py
import unittest, math import numpy as np from tinygrad.tensor import Tensor from tinygrad.nn.optim import AdamW from examples.mlperf.lr_schedulers import CosineAnnealingLRWithWarmup, LambdaLR, LambdaLinearScheduler np.random.seed(1337) x_init = np.random.randn(1,4).astype(np.float32) W_init = np.random.randn(4,4).asty...
68
2,659
tinygrad
test/external/external_test_jit_on_models.py
.py
#!/usr/bin/env python import unittest import numpy as np from tinygrad import Tensor, dtypes from tinygrad.engine.jit import TinyJit from tinygrad.helpers import Context from test.helpers import derandomize_model from examples.llama import Transformer def helper_test_jitted_correctness(gen, train, train_jit): nojit...
41
1,439
tinygrad
test/external/external_test_am_fault_recovery.py
.py
# ruff: noqa: F405 import unittest, subprocess, os from tinygrad.helpers import DEV from tinygrad.runtime.autogen.amd.rdna3.ins import * # noqa: F403 from tinygrad.renderer.amd.dsl import s, v, Inst, NULL def assemble_kernel(insts:list[Inst], name:str="test") -> str: kd = {"next_free_vgpr": 8, "next_free_sgpr": 8, ...
140
7,656
tinygrad
test/external/external_test_hcq_open.py
.py
import os if "DEV" not in os.environ: os.environ["DEV"] = "AMD" import unittest, time from tinygrad import Device class TestOpen(unittest.TestCase): def generate_test_open(n): def test(self): dev = Device[Device.DEFAULT] for i in range(10): dev.allocator.alloc(10 << 20) time.sleep(0....
21
496
tinygrad
test/external/external_test_keccak.py
.py
import unittest, zipfile, re from tinygrad import Tensor from tinygrad.helpers import fetch, tqdm SHA3_URL = "https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/sha3/sha-3bytetestvectors.zip" SHAKE_URL = "https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Vali...
32
1,586
tinygrad
test/external/external_jit_failure.py
.py
from tinygrad import Tensor, TinyJit, Device import numpy as np GPUS = 4 N = 128 ds = tuple([Device.canonicalize(f"{Device.DEFAULT}:{i}") for i in range(GPUS)]) t = Tensor.rand(N, N, N).shard(ds, 0) n = t.numpy() @TinyJit def allreduce(t:Tensor) -> Tensor: return t.sum(0) #.realize() for i in range(10): print(i)...
18
414
tinygrad
test/external/external_nhwc_conv.py
.py
from tinygrad import Tensor, nn, Context, GlobalCounters if __name__ == "__main__": conv = nn.Conv2d(64, 128, 3) img = Tensor.randn((1,64,128,128)) with Context(DEBUG=0, BEAM=0): Tensor.realize(img, conv.weight, conv.bias) tst = conv(img).permute(0,2,3,1).realize() print(tst.shape) print("NEW") img...
39
1,140
tinygrad
test/external/external_benchmark_kernel_launch.py
.py
import time from tinygrad import Tensor, TinyJit, Device, Context from tinygrad.helpers import Profiling, Timing, GlobalCounters # python3 test/speed/external_test_speed_v_torch.py TestSpeed.test_add_a @TinyJit def plus(a:Tensor, b:Tensor): return a+b if __name__ == "__main__": a = Tensor([1]).realize() b = Tens...
39
1,180
tinygrad
test/external/external_openpilot_image_warp.py
.py
import time from tinygrad.tensor import Tensor, Device MODEL_WIDTH = 512 MODEL_HEIGHT = 256 MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT * 3 // 2 IMG_INPUT_SHAPE = (1, 12, 128, 256) def tensor_arange(end): return Tensor([float(i) for i in range(end)]) def tensor_round(tensor:Tensor): return (tensor + 0.5).floor() h...
56
1,803
tinygrad
test/external/external_test_schedule_scaling.py
.py
import unittest, time, itertools from tinygrad import Tensor, Context class TestScheduleScaling(unittest.TestCase): """Test that .schedule() scales linearly with graph size (no O(n^2) behavior).""" def _assert_linear(self, fn, n_small=200, n_large=1000): """Assert schedule time scales at most ~linearly: time(...
148
5,675