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/external/external_test_hcq.py
.py
import unittest, ctypes, struct, time, array from tinygrad import Device, Tensor, dtypes from tinygrad.helpers import to_mv, DEV from tinygrad.device import Buffer, BufferSpec from tinygrad.engine.realize import get_runtime from tinygrad.codegen import to_program def _time_queue(q, d): st = time.perf_counter() q.s...
329
16,633
tinygrad
test/external/external_test_amd.py
.py
import unittest from tinygrad import Device, Tensor from tinygrad.schedule import create_schedule from tinygrad.runtime.ops_amd import AMDDevice class TestAMD(unittest.TestCase): @classmethod def setUpClass(self): TestAMD.d0: AMDDevice = Device["AMD"] TestAMD.a = Tensor([0.,1.], device="AMD").realize() ...
29
1,207
tinygrad
test/external/external_fuzz_tlsf.py
.py
import random from typing import Dict, Optional from tinygrad.helpers import getenv from tinygrad.runtime.support.memory import TLSFAllocator class AllocatorFuzzer: def __init__(self, total_size): self.total_size = total_size self.alloc_payload = 0 self.mv = memoryview(bytearray(total_size)) self.all...
82
2,748
tinygrad
test/external/external_model_benchmark.py
.py
import csv, pathlib, time import numpy as np import torch torch.set_num_threads(1) import onnxruntime as ort from onnx2torch import convert from tinygrad.nn.onnx import OnnxRunner from tinygrad.helpers import OSX, DEBUG, fetch, getenv from tinygrad.dtype import _to_np_dtype from tinygrad import Tensor, Device, Context,...
140
6,848
tinygrad
test/external/fuzz_symbolic.py
.py
# NOTE: z3-solver 4.15.4 segfaults (exit code 139) when creating many z3.Context() with complex expressions. # Reproduces consistently with seed=74 around iteration 1767. Versions <=4.15.3 are fine. # Workaround: reuse a single z3.Context, or pin z3-solver<4.15.4 (see pyproject.toml). # To repro: pip install z3-solver=...
93
4,890
tinygrad
test/external/external_gpu_fail_osx.py
.py
# ugh, OS X OpenCL doesn't support half from tinygrad.runtime.ops_cl import CLDevice, CLProgram, CLCompiler src = """#pragma OPENCL EXTENSION cl_khr_fp16 : enable __kernel void max_half(__global half* data0, const __global half* data1) { int gidx0 = get_group_id(0); data0[gidx0] = max(data1[gidx0], (half)0.0); }""...
16
535
tinygrad
test/external/external_test_process_count.py
.py
import os, sys, time, multiprocessing N = int(os.environ.get("NPROC", str(os.cpu_count()))) DEVICE = os.environ.get("DEV", "AMD") # this tests the total number of processes that can be running tinygrad at a time def proc(i, device, stop_evt): from tinygrad import Tensor try: a = Tensor.ones(2, device=device)...
58
1,696
tinygrad
test/external/external_test_speed_llama.py
.py
# NOTE: this only tests the speed of the LLaMA codegen, it doesn't actually run the net import unittest, time from examples.llama import Transformer, MODEL_PARAMS from tinygrad.tensor import Tensor from tinygrad import Device from tinygrad.nn.state import get_state_dict from tinygrad.device import Allocator, Compiled f...
59
2,376
tinygrad
test/external/external_fuzz_ampt.py
.py
import random from typing import Optional from tinygrad.helpers import round_up from tinygrad.runtime.support.am.amdev import AMPageTableTraverseContext from test.external.external_test_am import helper_read_entry_components, FakeAM class AMPTFuzzer: def __init__(self, total_size): self.total_size = total_size ...
110
4,160
tinygrad
test/external/external_test_llama3_layer.py
.py
#!/usr/bin/env python3 from tinygrad import Tensor, TinyJit, nn, dtypes from tinygrad.helpers import getenv from extra.models.llama import TransformerBlock, precompute_freqs_cis BS = getenv("BS", 1) SEQLEN = getenv("SEQLEN", 128) # DEFAULT_FLOAT=bfloat16 SEQLEN=8192 ASM_GEMM=1 HK_FLASH_ATTENTION=1 DEV=NULL:HIP:gfx950...
25
975
tinygrad
test/external/external_benchmark_llama_schedule.py
.py
from tinygrad import nn, Tensor, dtypes from tinygrad.helpers import DEV, Timing, Context from extra.models.llama import Transformer from examples.llama3 import MODEL_PARAMS if __name__ == "__main__": DEV.value = "NULL" #model_size = "8B" model_size = "405B" with Context(TRAINING=1), Timing("total "): wi...
35
1,181
tinygrad
test/external/external_uop_gc.py
.py
import gc from tinygrad import Tensor, UOp, Device, nn from tinygrad.schedule import schedule_cache from tinygrad.codegen import to_program, to_program_cache from tinygrad.schedule.indexing import apply_movement_op, _apply_reshape from tinygrad.uop.divandmod import fold_divmod_general from test.test_tiny import TestTin...
86
2,937
tinygrad
test/external/external_benchmark_all2all.py
.py
from tinygrad import Device, Tensor, TinyJit, dtypes from tinygrad.helpers import Timing, Context GPUS, DEPTH, SZ = 8, 4, 128 * 2**20 WARMUP, ITERS = 3, 5 devs = tuple(f"{Device.DEFAULT}:{i}" for i in range(GPUS)) bufs = tuple(Tensor.empty(SZ, dtype=dtypes.uint8, device=dev).contiguous().realize() for _ in range(DEPTH...
18
776
tinygrad
test/external/external_benchmark_keccak.py
.py
from tinygrad import Tensor, dtypes from tinygrad.engine.jit import TinyJit from tinygrad.helpers import Timing, getenv if __name__ == "__main__": BS = getenv("BS", 2**14) BLOCKSIZE = getenv("BLOCKSIZE", 4096) HASHFN = getenv("HASHFN", "shake_128") NRUNS = getenv("NRUNS", 5) @TinyJit def hasher(data: Tens...
21
727
tinygrad
test/external/external_osx_profiling.py
.py
from tinygrad.runtime.ops_cl import CLProgram, CL, CLBuffer from tinygrad import dtypes import time N = 1000000 a = CLBuffer(N, dtypes.float32) b = CLBuffer(N, dtypes.float32) c = CLBuffer(N, dtypes.float32) prg = CLProgram("test", """__kernel void test(__global float *a, __global float *b, __global float *c) { int...
42
1,191
tinygrad
test/external/external_test_onnx_backend.py
.py
import unittest from typing import Any, Tuple from onnx.backend.base import Backend, BackendRep import onnx.backend.test import numpy as np from tinygrad import Tensor, Device, dtypes from tinygrad.helpers import getenv, OSX from tinygrad.nn.onnx import OnnxRunner # pip3 install tabulate pytest_plugins = 'onnx.backend...
211
9,500
tinygrad
test/external/external_benchmark_schedule.py
.py
from extra.models.resnet import ResNet50 from tinygrad import Tensor, nn, Device from tinygrad.helpers import Profiling, Timing, getenv from tinygrad.uop.ops import Ops from tinygrad.codegen import full_rewrite_to_sink from tinygrad.codegen.late.linearizer import linearize from tinygrad.uop.spec import type_verify, spe...
46
1,762
tinygrad
test/external/external_fuzz_qcom_cpu_cache.py
.py
#!/usr/bin/env python3 from tinygrad.tensor import Tensor import numpy as np while True: arr = np.ones(1000000, dtype=np.uint8) print(f"numpy: {(arr + 1)[:10]}") ptr = arr.ctypes.data tensor = Tensor.from_blob(ptr, arr.shape, dtype='uint8', device='QCOM').realize() + 1 print(f"from_blob: {tensor.numpy()[:10...
12
325
tinygrad
test/external/external_test_tlsf.py
.py
import unittest from tinygrad.runtime.support.memory import TLSFAllocator class TestTLSFAllocator(unittest.TestCase): def setUp(self): self.allocator = TLSFAllocator(1024, block_size=16) def test_basic_alloc_free(self): addr1 = self.allocator.alloc(32) self.assertEqual(addr1, 0) addr2 = self.allo...
79
2,222
tinygrad
test/external/mlperf_retinanet/presets.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/presets.py from test.external.mlperf_retinanet import transforms as T class DetectionPresetTrain: def __init__(self, data_augmentation, hflip_prob=0.5, mean=(123., 117., 104.)): if d...
24
847
tinygrad
test/external/mlperf_retinanet/transforms.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/transforms.py import torch import torchvision from torch import nn, Tensor from torchvision.transforms import functional as F from torchvision.transforms import transforms as T from typing impor...
77
2,469
tinygrad
test/external/mlperf_retinanet/openimages.py
.py
from test.external.mlperf_retinanet.model.boxes import box_iou from test.external.mlperf_retinanet.model.utils import Matcher import torch # This applies the filtering in https://github.com/mlcommons/training/blob/cdd928d4596c142c15a7d86b2eeadbac718c8da2/single_stage_detector/ssd/model/retinanet.py#L117 # and https:/...
26
1,506
tinygrad
test/external/mlperf_retinanet/focal_loss.py
.py
# Copied from https://github.com/mlcommons/training/blob/cdd928d4596c142c15a7d86b2eeadbac718c8da2/single_stage_detector/ssd/model/focal_loss.py import torch import torch.nn.functional as F def sigmoid_focal_loss( inputs: torch.Tensor, targets: torch.Tensor, alpha: float = 0.25, gamma: float = 2, ...
51
1,890
tinygrad
test/external/mlperf_retinanet/coco_utils.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/coco_utils.py import os import torch import torchvision from test.external.mlperf_retinanet import transforms as T class ConvertCocoPolysToMask(object): def __init__(self, filter_iscrowd=Tr...
89
3,002
tinygrad
test/external/mlperf_retinanet/model/transform.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/model/transform.py import torch from torch import nn, Tensor from typing import List, Tuple, Dict, Optional from test.external.mlperf_retinanet.model.image_list import ImageList @torch.jit.unu...
163
6,787
tinygrad
test/external/mlperf_retinanet/model/utils.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/model/utils.py import torch class Matcher(object): """ This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly z...
123
5,465
tinygrad
test/external/mlperf_retinanet/model/image_list.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/model/image_list.py import torch from torch import Tensor from typing import List, Tuple class ImageList(object): """ Structure that holds a list of images (of possibly varying size...
27
886
tinygrad
test/external/mlperf_retinanet/model/boxes.py
.py
# Copied from https://github.com/mlcommons/training/blob/637c82f9e699cd6caf108f92efb2c1d446b630e0/single_stage_detector/ssd/model/boxes.py import torch from torch import Tensor from typing import Tuple def _upcast(t: Tensor) -> Tensor: # Protects from numerical overflows in multiplications by upcasting to the equ...
65
2,210
tinygrad
test/external/sglang_llama/external_llama_eval.py
.py
from lm_eval import simple_evaluate from lm_eval.api.instance import Instance from lm_eval.api.model import LM from lm_eval.tasks import TaskManager from pathlib import Path import json, argparse from examples.llama3 import build_transformer, Tokenizer, MODEL_PARAMS from tinygrad import Tensor, Device from tinygrad.he...
101
4,885
tinygrad
test/external/mlperf_bert/external_test_checkpoint_loading.py
.py
# Test whether pretrained weights from first BERT pretraining phase have been loaded correctly # Usage: # 1. Download the BERT checkoints with `wikipedia_download.py` # Command: BASEDIR=/path/to/wiki python3 wikipedia_download.py # 2. Run this script. (Adjust EVAL_BS and GPUS as needed) # Command: EVAL_BEAM=4 DEF...
54
2,675
tinygrad
test/external/mlperf_bert/external_benchmark_bert.py
.py
import unittest, time from tinygrad import Tensor, TinyJit, GlobalCounters, Device from tinygrad.helpers import getenv, Context from tinygrad.nn.optim import LAMB from tinygrad.nn.state import get_parameters from tinygrad.engine.realize import run_linear from extra.models import bert bs = getenv("BS", 16) seq_len = ...
103
4,361
tinygrad
test/external/mlperf_bert/preprocessing/tokenization.py
.py
# https://github.com/mlcommons/training/blob/1c8a098ae3e70962a4f7422c0b0bd35ae639e357/language_model/tensorflow/bert/cleanup_scripts/tokenization.py # NOTE: This is a direct copy of the original script """Tokenization classes.""" from __future__ import absolute_import from __future__ import division from __future__ im...
416
12,706
tinygrad
test/external/mlperf_bert/preprocessing/pick_eval_samples.py
.py
# https://github.com/mlcommons/training/blob/1c8a098ae3e70962a4f7422c0b0bd35ae639e357/language_model/tensorflow/bert/cleanup_scripts/pick_eval_samples.py # NOTE: This is a direct copy of the original script """Script for picking certain number of sampels. """ import argparse import time import logging import collectio...
128
4,026
tinygrad
test/external/mlperf_bert/preprocessing/create_pretraining_data.py
.py
# https://github.com/mlcommons/training/blob/1c8a098ae3e70962a4f7422c0b0bd35ae639e357/language_model/tensorflow/bert/cleanup_scripts/create_pretraining_data.py # NOTE: This is a direct copy of the original script # NOTE: With python 3.7.12, pip install tensorflow=1.15.5 """Create masked LM/next sentence masked_lm TF ex...
436
15,017
tinygrad
test/external/mlperf_bert/preprocessing/external_test_preprocessing_part.py
.py
# USAGE: # 1. Download raw text data with `wikipedia_download.py` # 2. Install python==3.7.12 and tensorflow==1.15.5 # Run `create_pretraining_data.py` to create TFRecords on specific part (This will take some time) # Command: python3 create_pretraining_data.py --input_file=/path/to/part-00XXX-of-00500 --voc...
80
4,841
tinygrad
test/external/mlperf_resnet/lars_util.py
.py
# https://github.com/mlcommons/training/blob/e237206991d10449d9675d95606459a3cb6c21ad/image_classification/tensorflow2/lars_util.py # changes: commented out logging # changes: convert_to_tensor_v2 -> convert_to_tensor # changes: extend from tf.python.keras.optimizer_v2.learning_rate_schedule.LearningRateScheduler # Co...
180
6,557
tinygrad
test/external/mlperf_resnet/lars_optimizer.py
.py
# https://github.com/mlcommons/training/blob/e3769c8dcf88cd21e1001dd2f894b40a1513ec5d/image_classification/tensorflow2/lars_optimizer.py # changes: don't call lr_t if it's not a schedule # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # ...
220
8,842
tinygrad
test/external/process_replay/reset.py
.py
#!/usr/bin/env python3 from tinygrad.helpers import db_connection, VERSION cur = db_connection() cur.execute(f"drop table if exists process_replay_{VERSION}")
5
159
tinygrad
test/external/process_replay/process_replay.py
.py
#!/usr/bin/env python3 # compare kernels created by HEAD against master import os, multiprocessing, logging, pickle, sqlite3, difflib, warnings, functools, base64, codecs from dataclasses import replace from typing import Callable, Any ASSERT_DIFF = int((flag:="[PR]") in os.getenv("COMMIT_MESSAGE", flag) or flag in os...
129
5,386
tinygrad
test/external/mlperf_unet3d/kits19.py
.py
# copied from https://github.com/mlcommons/training/blob/5c08ce57e7f582cc4558035d8324a2bf4c8ca225/image_segmentation/pytorch/data_loading/pytorch_loader.py import random import numpy as np import scipy.ndimage from torch.utils.data import Dataset from torchvision import transforms def get_train_transforms(): ran...
165
6,133
tinygrad
test/external/mlperf_unet3d/dice.py
.py
# https://github.com/mlcommons/training/blob/master/image_segmentation/pytorch/model/losses.py import torch import torch.nn as nn import torch.nn.functional as F class Dice: def __init__(self, to_onehot_y: bool = True, to_onehot_x: bool = False, use_softmax: bool = True...
95
3,438
tinygrad
test/external/mlperf_stable_diffusion/external_test_eval.py
.py
import unittest, os import numpy as np from pathlib import Path from tempfile import TemporaryDirectory from tinygrad import Device, Tensor from tinygrad.helpers import getenv, Context from tinygrad.nn.state import safe_save, torch_load, get_parameters from examples.mlperf.model_eval import eval_stable_diffusion, vae_d...
58
3,250
tinygrad
test/external/mlperf_stable_diffusion/external_test_train.py
.py
import unittest, os from tempfile import TemporaryDirectory from tinygrad import Context from tinygrad.helpers import getenv from examples.mlperf.model_train import train_stable_diffusion class TestTrain(unittest.TestCase): def test_train_to_ckpt(self): # train for num_steps, save checkpoint, and stop training ...
24
1,079
tinygrad
test/external/mlperf_stable_diffusion/external_test_models.py
.py
import unittest import numpy as np from pathlib import Path from tinygrad import Tensor, dtypes, Device from tinygrad.helpers import getenv from tinygrad.nn.state import get_parameters from extra.models import clip from examples.mlperf.initializers import gelu_erf, init_stable_diffusion, attn_f32_softmax from typing im...
114
6,395
tinygrad
test/opt/test_kernel_opts.py
.py
import unittest from tinygrad import Device, Tensor, dtypes from tinygrad.codegen.opt import Opt, OptOps, KernelOptError # TODO: write a clean version of this from test.backend.test_linearizer import helper_linearizer_opt class TestKernelOpts(unittest.TestCase): @unittest.skipUnless(Device[Device.DEFAULT].renderer....
364
18,684
tinygrad
test/opt/test_tensor_cores.py
.py
import numpy as np import unittest from tinygrad import Device, Tensor, dtypes from tinygrad.tensor import _to_np_dtype from tinygrad.uop.ops import Ops, UOp, buffers from tinygrad.dtype import DType from tinygrad.device import Buffer from tinygrad.helpers import DEV, Context from test.helpers import slow, replace_opt...
230
13,911
tinygrad
test/opt/test_gen_float4.py
.py
import unittest from tinygrad import Device, Tensor, Variable, dtypes from tinygrad.uop.ops import UOp, Ops from tinygrad.codegen import to_program from tinygrad.codegen.opt import Opt, OptOps from test.helpers import replace_opts @unittest.skipUnless(Device[Device.DEFAULT].renderer.supports_float4, "need backends th...
145
6,018
tinygrad
test/backend/test_linearizer_dumb.py
.py
# ruff: noqa: E501 # tests where the Linearizer is doing something dumb # like test_linearizer_failures, but they don't have to fail import unittest from tinygrad import Device, dtypes from tinygrad.uop.ops import UOp, Ops, AxisType, KernelInfo from tinygrad.codegen.opt.search import Opt, OptOps from tinygrad.codegen ...
32
1,805
tinygrad
test/backend/test_llama_kernels.py
.py
import unittest, functools from tinygrad import Tensor, Device, dtypes, Context, GlobalCounters from tinygrad.helpers import getenv from examples.mlperf.models.flat_llama import FP8_DTYPE, quantize_fp8 from extra.llama_kernels.fused_ce import fused_ce_loss from extra.llama_kernels import local_abs_max from extra.llama_...
193
9,503
tinygrad
test/backend/test_custom_kernel.py
.py
import unittest from tinygrad import Tensor, UOp, GlobalCounters, Context, Device import numpy as np from tinygrad.dtype import AddrSpace, dtypes, Invalid from tinygrad.uop.ops import KernelInfo, AxisType, Ops from tinygrad.renderer.ptx import PTXRenderer from test.helpers import assert_kernel_count # **** kernels ***...
697
31,058
tinygrad
test/backend/test_encodings.py
.py
import unittest from tinygrad import Device from tinygrad.uop.ops import UOp, Ops from tinygrad.dtype import dtypes from tinygrad.renderer.isa.x86 import X86Ops, X86Renderer, RBP, RDI, RSP, RSI, RAX, RDX, XMM, GPR, imm, def_reg def ins(op, dt, src, tag=None): return UOp(Ops.INS, arg=op, dtype=dt, src=src, tag=tag) @u...
151
8,157
tinygrad
test/backend/test_stunning.py
.py
import unittest from tinygrad import nn, Tensor, Variable, Context, Device from tinygrad.helpers import trange class Model: def __init__(self): self.layer = nn.Linear(28*28, 10) def __call__(self, x:Tensor) -> Tensor: return self.layer(x.flatten(1)) class TestStunning(unittest.TestCase): def test_indexing_varia...
60
2,083
tinygrad
test/backend/test_interop.py
.py
#!/usr/bin/env python import unittest, os import torch import numpy as np from tinygrad.helpers import DEV from tinygrad.tensor import Tensor from tinygrad.device import Device from tinygrad.dtype import _from_torch_dtype, _to_torch_dtype MOCKGPU = DEV.interface.startswith("MOCK") @unittest.skipIf(Device.DEFAULT not...
53
1,948
tinygrad
test/backend/test_zero_copy.py
.py
import unittest from tinygrad import Tensor, Device import time def time_tensor_numpy(out:Tensor): times = [] for _ in range(5): st = time.perf_counter() out.uop.base.realized.as_memoryview(allow_zero_copy=True) et = time.perf_counter() - st times.append(et) return min(times) N = 4096 class Test...
28
892
tinygrad
test/backend/test_dtype.py
.py
import contextlib, unittest, math import numpy as np import torch from typing import Any, List from tinygrad.helpers import getenv, DEBUG, EMULATED_DTYPES, DEV from tinygrad.dtype import DType, DTYPES_DICT, least_upper_dtype, fp8_to_float, float_to_fp8, _to_np_dtype, _to_torch_dtype, truncate from tinygrad.renderer.ptx...
439
21,296
tinygrad
test/backend/test_uops.py
.py
from typing import Optional, Any import unittest, math import numpy as np from tinygrad.tensor import Tensor, _to_np_dtype from tinygrad.helpers import Context from tinygrad.dtype import dtypes, DType, AddrSpace, ConstFloat # noqa: F401 from tinygrad.device import Buffer, Device from tinygrad.uop.ops import Ops, UOp, ...
346
17,190
tinygrad
test/backend/test_graph.py
.py
import numpy as np import functools, unittest from tinygrad.device import Device, Buffer from tinygrad.tensor import Tensor from tinygrad.helpers import Context from tinygrad.dtype import dtypes from tinygrad.engine.jit import MultiGraphRunner from tinygrad.engine.realize import run_linear, compile_linear from tinygra...
320
12,140
tinygrad
test/backend/test_asm_gemm.py
.py
import unittest from tinygrad import Tensor, Device, dtypes, Context from tinygrad.helpers import getenv, system, DEV from extra.gemm.cdna_asm_gemm import asm_gemm, hk_bf16_atb_gemm from test.helpers import needs_second_gpu from examples.mlperf.models.flat_llama import FP8_DTYPE, quantize_fp8, FP8_MAX # On non CDNA4 i...
427
22,871
tinygrad
test/backend/test_tensor.py
.py
import numpy as np import torch import unittest, copy, mmap, random, math, array from tinygrad import Tensor, Device, dtypes, nn, Context from tinygrad.helpers import getenv, temp, mv_address from extra.gradcheck import numerical_jacobian, jacobian, gradcheck from hypothesis import given, settings, strategies as strat ...
788
31,230
tinygrad
test/backend/test_const_folding.py
.py
import unittest, math from tinygrad import Tensor, Device, dtypes from tinygrad.dtype import DTYPES_DICT from tinygrad.uop.ops import Ops, UOp from tinygrad.codegen.decomp.op import threefry2x32 import numpy as np from test.helpers import not_support_multi_device def _check_ast_count(desired_count:int, t:Tensor): # ...
211
9,546
tinygrad
test/backend/test_randomness.py
.py
import unittest, math from tinygrad import dtypes, Tensor, Device from tinygrad.helpers import getenv, DEV, Context from tinygrad.codegen import to_program from tinygrad.uop.ops import Ops from tinygrad.renderer.ptx import PTXRenderer from tinygrad.renderer.nir import NIRRenderer from tinygrad.renderer.isa.x86 import...
261
11,154
tinygrad
test/backend/test_ops.py
.py
import time, math, unittest, functools, platform, warnings, sys import numpy as np from typing import List, Callable import torch from tinygrad.helpers import getenv, DEBUG, DEV, IMAGE, Context from tinygrad import Tensor, Device, dtypes from tinygrad.tensor import _to_np_dtype from tinygrad.renderer.nir import NIRRend...
3,434
202,059
tinygrad
test/backend/test_transcendental.py
.py
import unittest from tinygrad import Tensor, Device, dtypes from tinygrad.tensor import _to_np_dtype from tinygrad.helpers import Context, getenv, DEV, OSX from test.helpers import check_schedule from test.backend.test_dtype_alu import ht, dtypes_float import numpy as np import math from hypothesis import given, settin...
206
9,990
tinygrad
test/backend/test_call.py
.py
import unittest, ctypes from tinygrad import Tensor, UOp from tinygrad.device import Device from tinygrad.dtype import dtypes from tinygrad.renderer.cstyle import CStyleLanguage from tinygrad.uop.ops import KernelInfo def call_out_kernel(F:UOp, C:UOp) -> UOp: call = F[0].load().call(UOp.const(3).cast(dtypes.int), C[...
40
1,665
tinygrad
test/backend/test_schedule.py
.py
# this will be the new test_ops for the next level # schedule confirms the right things are capable of fusing # NOTE: this has overlap with external_test_opt.py import unittest, time import numpy as np from tinygrad import nn, dtypes, Device, Tensor, Variable from tinygrad.uop.ops import Ops, UPat from tinygrad.helpe...
485
19,486
tinygrad
test/backend/test_profiler.py
.py
import unittest, struct, contextlib, statistics, gc from tinygrad import Device, Tensor, dtypes, TinyJit from tinygrad.helpers import DEV, Context, ProfileRangeEvent, cpu_profile, cpu_events, ProfilePointEvent, dedup from tinygrad.device import Buffer, BufferSpec, Compiled, ProfileDeviceEvent, ProfileGraphEvent from ti...
228
11,285
tinygrad
test/backend/test_edgecases.py
.py
# end to end tests of tinygrad that you think might be edge cases. # using the documentation, write code you think should work. # you can compare the outputs to torch or numpy, or just tinygrad assert/raise while doing things that should be valid # i'm not interested in tests that currently pass, i'm only interested i...
247
10,673
tinygrad
test/backend/test_multitensor.py
.py
import unittest, random from tinygrad import Tensor, Device, nn, GlobalCounters, TinyJit, dtypes, Variable from tinygrad.uop.ops import Ops, UOp, AxisType, graph_rewrite from tinygrad.helpers import getenv, prod, Context from tinygrad.nn.state import get_parameters from tinygrad.engine.realize import run_linear, compil...
537
21,753
tinygrad
test/backend/test_subbuffer.py
.py
import unittest from tinygrad import Device, dtypes, Tensor from tinygrad.device import Buffer from tinygrad.helpers import Context, DEV from test.helpers import needs_second_gpu @unittest.skipIf(Device.DEFAULT in {"WEBGPU", "CL"}, "subbuffer not supported") class TestSubBuffer(unittest.TestCase): def setUp(self): ...
184
7,028
tinygrad
test/backend/test_to_numpy.py
.py
from tinygrad.tensor import Tensor import numpy as np import pickle import unittest class TestToNumpy(unittest.TestCase): def test_numpy_is_numpy(self): output = Tensor.ones((1, 3, 4096)).realize().numpy() new = np.copy(output) print(type(new)) serialized = pickle.dumps(new) out = pickle.loads(se...
17
436
tinygrad
test/backend/test_quantize_onnx.py
.py
# ruff: noqa: E501 import numpy as np import tempfile, unittest from tinygrad import Tensor, Context, Device, dtypes, UOp from tinygrad.uop.ops import Ops from tinygrad.dtype import AddrSpace from tinygrad.codegen.opt import Opt, OptOps from tinygrad.engine.realize import run_linear from tinygrad.codegen import to_prog...
240
12,398
tinygrad
test/backend/test_isel.py
.py
import unittest from typing import cast from tinygrad import Device from tinygrad.uop import Ops from tinygrad.uop.ops import UOp, dtypes, graph_rewrite from tinygrad.renderer.isa.x86 import X86Renderer, X86Ops from tinygrad.renderer.isa import IselContext # INDEX on a register value with a constant index extracts a s...
56
2,405
tinygrad
test/backend/test_softmax_fusion.py
.py
import unittest import numpy as np from tinygrad import Tensor, GlobalCounters, Context, Device from tinygrad.dtype import DTypeLike, dtypes from tinygrad.engine.realize import run_linear from tinygrad.helpers import DEBUG, get_single_element from test.helpers import check_schedule def single_kernel_softmax(x_in:Tenso...
207
7,332
tinygrad
test/backend/test_tensor_variable.py
.py
import unittest import numpy as np from tinygrad import Device, Tensor, Variable, TinyJit, dtypes from tinygrad.helpers import CHECK_OOB class TestTensorVariable(unittest.TestCase): def test_add_tvar(self): vv = Variable("a", 0, 10).bind(1) ret = (Tensor(vv) + 3).item() assert ret == 4 def test_variab...
222
9,187
tinygrad
test/backend/test_rangeify.py
.py
import unittest from tinygrad import Tensor, nn, Device, dtypes, Variable from tinygrad.helpers import Context, GlobalCounters, getenv, PCONTIG, DEBUG from tinygrad.uop.ops import graph_rewrite, PatternMatcher, UPat, Ops, UOp from tinygrad.codegen.opt import OptOps, Opt from tinygrad.renderer.ptx import PTXRenderer fro...
235
9,521
tinygrad
test/backend/test_renderer_failures.py
.py
import unittest import numpy as np from tinygrad.device import Device, Buffer from tinygrad.dtype import dtypes, ConstType from tinygrad.engine.realize import run_linear from tinygrad.codegen import to_program from tinygrad.helpers import prod from tinygrad.renderer.cstyle import CStyleLanguage from tinygrad.renderer.p...
124
6,565
tinygrad
test/backend/test_pickle.py
.py
import unittest, pickle, types, tracemalloc import numpy as np from tinygrad import Tensor, Device, TinyJit, Variable, dtypes from tinygrad.helpers import GlobalCounters, ContextVar, Context, DEV from tinygrad.uop.ops import PatternMatcher, UPat, UOp, deconstruct_function class TestPickle(unittest.TestCase): def tes...
202
6,794
tinygrad
test/backend/test_dtype_alu.py
.py
import unittest, operator, math from tinygrad import Context, Tensor, dtypes, Device from tinygrad.dtype import DType, truncate, fp8_to_float from tinygrad.helpers import EMULATED_DTYPES, DEV, getenv from tinygrad.tensor import _to_np_dtype from tinygrad.runtime.ops_python import from_storage_scalar from tinygrad.rende...
412
23,717
tinygrad
test/backend/test_optim.py
.py
import numpy as np import torch import unittest from tinygrad import Tensor, Device, dtypes from tinygrad.nn.optim import Adam, SGD, AdamW, Muon, LAMB from tinygrad.helpers import Context from test.helpers import needs_second_gpu, slow np.random.seed(1337) x_init = np.random.randn(1,4).astype(np.float32) W_init = np.r...
190
9,016
tinygrad
test/backend/test_arange.py
.py
import unittest import numpy as np from tinygrad import Tensor, GlobalCounters, dtypes, nn, Device, Variable from tinygrad.helpers import Context, getenv, DEV from tinygrad.engine.realize import run_linear, estimate_uop, compile_linear from tinygrad.renderer.ptx import PTXRenderer from test.helpers import needs_second_...
270
12,758
tinygrad
test/backend/test_symbolic_ops.py
.py
import unittest from tinygrad import Tensor, Variable, GlobalCounters, Context from tinygrad.uop.ops import sym_infer from tinygrad.dtype import dtypes from examples.gpt2 import Attention import numpy as np class TestSymbolicOps(unittest.TestCase): def test_negative_slice(self): a = Tensor.rand(3, 10, 4) for...
368
14,742
tinygrad
test/backend/test_opt_gemm.py
.py
import numpy as np import unittest from tinygrad import Tensor from tinygrad.helpers import get_single_element from tinygrad.codegen.opt import Opt, OptOps from tinygrad.engine.realize import run_linear from tinygrad.uop.ops import Ops, UOp from test.helpers import replace_opts class TestOptGemm(unittest.TestCase): ...
47
1,826
tinygrad
test/backend/test_symbolic_jit.py
.py
import unittest from test.helpers import assert_jit_cache_len from tinygrad import Variable, Tensor, TinyJit from tinygrad.engine.jit import JitError import numpy as np class TestSymbolicJit(unittest.TestCase): def test_plus1(self): def f(a): return (a+1).realize() jf = TinyJit(f) a = Tensor.rand(3, 10)...
333
11,780
tinygrad
test/backend/test_setitem.py
.py
import unittest from tinygrad import Tensor, TinyJit, Variable, dtypes, Device from tinygrad.helpers import Context import numpy as np class TestSetitem(unittest.TestCase): def test_simple_setitem(self): cases = ( ((6,6), (slice(2,4), slice(3,5)), Tensor.ones(2,2)), ((6,6), (slice(2,4), slice(3,5)), ...
379
13,688
tinygrad
test/backend/test_jit.py
.py
#!/usr/bin/env python import unittest import numpy as np from test.helpers import assert_jit_cache_len, call_is_graph, not_support_multi_device, needs_second_gpu, KernelCountException from test.unit.test_jit import _simple_test from tinygrad import Tensor, Variable, TinyJit, Device, dtypes from tinygrad.engine.jit imp...
451
16,578
tinygrad
test/backend/test_linearizer.py
.py
import numpy as np import unittest from tinygrad.codegen.opt import Opt, OptOps from tinygrad.uop.ops import UOp, Ops, GroupOp, AxisType, buffers from tinygrad.device import Device, Buffer from tinygrad.tensor import Tensor, _to_np_dtype from tinygrad.engine.realize import run_linear from tinygrad.codegen import to_pr...
468
25,705
tinygrad
test/backend/test_nn.py
.py
#!/usr/bin/env python import unittest import numpy as np import torch from tinygrad import Tensor, Device, TinyJit, dtypes from tinygrad.helpers import GlobalCounters, Context from tinygrad.nn import Conv1d, ConvTranspose1d, Conv2d, ConvTranspose2d, Linear, Embedding from tinygrad.nn import BatchNorm, LayerNorm, LayerN...
621
25,317
tinygrad
test/backend/test_wait_loop.py
.py
import unittest, threading from tinygrad import Tensor, UOp from tinygrad.device import Device, Buffer, BufferSpec from tinygrad.dtype import AddrSpace, dtypes from tinygrad.engine.realize import run_linear from tinygrad.uop.ops import Ops, KernelInfo def wait_loop_kernel(C:UOp) -> UOp: N = 10 # a RANGE with no s...
128
4,381
tinygrad
test/models/test_rnnt.py
.py
#!/usr/bin/env python import unittest from tinygrad import Tensor from extra.models.rnnt import LSTM import numpy as np import torch class TestRNNT(unittest.TestCase): def test_lstm(self): BS, SQ, IS, HS, L = 2, 20, 40, 128, 2 # create in torch with torch.no_grad(): torch_layer = torch.nn.LSTM(IS,...
48
1,701
tinygrad
test/models/test_waifu2x.py
.py
#!/usr/bin/env python import pathlib import unittest import numpy as np from tinygrad.tensor import Tensor class TestVGG7(unittest.TestCase): def test_vgg7(self): from examples.vgg7_helpers.waifu2x import Vgg7, image_load # Create in tinygrad Tensor.manual_seed(1337) mdl = Vgg7() mdl.load_from_p...
25
715
tinygrad
test/models/test_efficientnet.py
.py
import ast, pathlib, unittest import numpy as np from PIL import Image from tinygrad import Tensor, Context from tinygrad.helpers import getenv from test.helpers import slow from extra.models.efficientnet import EfficientNet from extra.models.vit import ViT from extra.models.resnet import ResNet50 def _load_labels()...
115
3,348
tinygrad
test/models/test_end2end.py
.py
import torch from torch import nn import unittest, sys import numpy as np from tinygrad.nn.state import get_parameters, get_state_dict from tinygrad.nn import optim, Linear, Conv2d, BatchNorm2d from tinygrad.tensor import Tensor from tinygrad.helpers import Context from extra.datasets import fetch_mnist def compare_ti...
165
6,252
tinygrad
test/models/test_bert.py
.py
#!/usr/bin/env python import os os.environ['USE_TF'] = '0' # prevent transformers from importing tensorflow import unittest from tinygrad import Tensor import numpy as np import torch def get_question_samp(bsz, seq_len, vocab_size, seed): np.random.seed(seed) in_ids = np.random.randint(vocab_size, size=(bsz, seq_...
59
2,182
tinygrad
test/models/test_mnist.py
.py
#!/usr/bin/env python import unittest import numpy as np from tinygrad import Tensor from test.helpers import slow from tinygrad.nn.state import get_parameters from tinygrad.nn import optim, BatchNorm2d from extra.training import train, evaluate from extra.datasets import fetch_mnist # load the mnist dataset X_train, ...
116
3,803
tinygrad
test/models/test_train.py
.py
import unittest, time import numpy as np from tinygrad import Device from tinygrad.nn.state import get_parameters from tinygrad.nn import optim from tinygrad.helpers import getenv from test.helpers import slow from extra.training import train from extra.models.convnext import ConvNeXt from extra.models.efficientnet imp...
84
2,347
tinygrad
test/models/test_onnx.py
.py
#!/usr/bin/env python import unittest import numpy as np from tinygrad.nn.onnx import OnnxRunner from tinygrad.device import Device from tinygrad.helpers import fetch, Context from extra.onnx_helpers import validate from extra.huggingface_onnx.huggingface_manager import DOWNLOADS_DIR, snapshot_download_with_retry def...
94
3,411
tinygrad
test/models/test_whisper.py
.py
import unittest import pathlib from examples.whisper import init_whisper, load_file_waveform, transcribe_file, transcribe_waveform from examples.audio_helpers import mel import examples.mlperf.metrics as metrics from tinygrad.helpers import fetch from test.helpers import slow from tinygrad import Tensor, Device, dtypes...
156
7,537
tinygrad
test/speed/external_test_copy_speed.py
.py
import unittest, numpy as np, os from tinygrad import Tensor, Device, TinyJit from tinygrad.helpers import Timing, getenv import multiprocessing.shared_memory as shared_memory N = getenv("NSZ", 256) class TestCopySpeed(unittest.TestCase): @classmethod def setUpClass(cls): Device[Device.DEFAULT].synchronize() de...
92
3,565
tinygrad
test/speed/external_test_speed_v_torch.py
.py
import os os.environ["NVIDIA_TF32_OVERRIDE"] = "0" os.environ["MKL_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["OMP_NUM_THREADS"] = "1" os.environ["VECLIB_MAXIMUM_THREADS"] = "1" import unittest import torch torch.set_num_threads(1) import time import numpy as np import sys np.set_printoption...
289
11,786
tinygrad
test/speed/external_test_specific_conv.py
.py
import unittest from tinygrad import Tensor, Device, dtypes from tinygrad.helpers import DEV # similar to test/external/external_test_gpu_ast.py, but universal @unittest.skipIf(Device.DEFAULT in {"CUDA", "NV"} and DEV.interface.startswith("MOCK"), "slow on ocelot") class TestSpecific(unittest.TestCase): # from openp...
55
2,352