repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
tinygrad | extra/thunder/tiny/tk/tiles.py | .py | from enum import Enum, auto
import functools
from typing import Callable
from dataclasses import dataclass
from tinygrad.dtype import AddrSpace, DType
from tinygrad.mixin.elementwise import ElementwiseMixin
from tinygrad.uop.ops import UOp, Ops
from extra.thunder.tiny.tk import WARP_THREADS
def unwrap(x):
if hasatt... | 277 | 9,782 |
tinygrad | extra/thunder/metal/gemm.py | .py | # include directory copied from https://github.com/HazyResearch/ThunderMittens
# https://hazyresearch.stanford.edu/blog/2024-11-28-tk-mlx
gemm = """
#include <metal_stdlib>
#include "include/tk.metal"
using namespace mittens;
#define GEMM_PARAMS_DEF(T) \
device T* D [[buffer(0)]], \
device T* A [[buffer(1)]],... | 75 | 2,407 |
tinygrad | extra/thunder/amd/fa.py | .py | import math, pathlib, functools, struct
from tinygrad import Device, Tensor
from tinygrad.dtype import DTypeLike, dtypes
from tinygrad.helpers import DEBUG, getenv
from tinygrad.renderer import Estimates
from tinygrad.runtime.support.compiler_amd import HIPCCCompiler
from tinygrad.runtime.support.elf import elf_loader... | 358 | 21,103 |
tinygrad | extra/thunder/cuda/fa.py | .py | import pathlib
from tinygrad import Device, Tensor
from tinygrad.helpers import Context
from tinygrad.runtime.support.compiler_cuda import pretty_ptx, NVCCCompiler
if __name__ == "__main__":
code = (pathlib.Path(__file__).parent / "fa.cu").read_text()
device = Device["CUDA"]
kitten_args = [f"-I{(pathlib.Path(__f... | 44 | 1,666 |
tinygrad | extra/thunder/cuda/matmul.py | .py | import pathlib
from tinygrad import Device, Tensor
from tinygrad.helpers import Context, getenv
from tinygrad.runtime.support.compiler_cuda import pretty_ptx, NVCCCompiler
if __name__ == "__main__":
if getenv("MATMUL2"):
code = (pathlib.Path(__file__).parent / "matmul2.cu").read_text()
else:
code = (pathli... | 56 | 1,788 |
tinygrad | extra/mmapeak/mmapeak.py | .py | import os
# TODO: there is a timing bug without this
os.environ["AMD_AQL"] = "1"
from tinygrad import Tensor, Device, GlobalCounters, Context
from tinygrad.helpers import getenv, DEV
from tinygrad.uop.ops import UOp, Ops, KernelInfo
from tinygrad.renderer import Estimates
from tinygrad.renderer.amd.dsl import Reg, In... | 113 | 5,668 |
tinygrad | extra/mlx_driver/loopback.py | .py | #!/usr/bin/env python3
# GMMU=0 MLX_PCI=0000:41:00.0 PYTHONPATH=. python3 extra/mlx_driver/loopback.py
import struct
from tinygrad.helpers import getenv, round_up
from tinygrad.device import Device, BufferSpec
from tinygrad.runtime.support.system import PCIDevice
from tinygrad.runtime.support.memory import AddrSpace
fr... | 100 | 3,898 |
tinygrad | extra/mlx_driver/connect.py | .py | #!/usr/bin/env python3
import subprocess, json, sys, os
REMOTE_HOST = os.getenv("REMOTE_HOST", "192.168.52.154")
LOCAL_PCI = os.getenv("MLX_PCI", "0000:41:00.0")
REMOTE_PCI = os.getenv("REMOTE_PCI", "0000:41:00.0")
LOCAL_IP = os.getenv("LOCAL_IP", "10.0.0.1")
REMOTE_IP = os.getenv("REMOTE_IP", "10.0.0.2")
SSH ... | 69 | 2,723 |
tinygrad | extra/remote/bench.py | .py | #!/usr/bin/env python3
import os, sys, time
from tinygrad.runtime.support.system import RemotePCIDevice
LAT_N_RUNS = 500
THROUGHPUT_N_RUNS = 8
SIZES = [4, 1 << 10, 8 << 20]
if __name__ == "__main__":
os.environ["REMOTE"] = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("REMOTE", "127.0.0.1:6667")
# choose ... | 48 | 1,838 |
tinygrad | extra/remote/serve.py | .py | #!/usr/bin/env python3
import socket, struct, sys
from tinygrad.runtime.support.system import PCIDevice, RemoteCmd, System
from tinygrad.helpers import DEBUG, OSX
def resp(resp0=0, resp1=0, status=0): return struct.pack('<BQQ', status, resp0, resp1)
def resp_err(msg): return struct.pack('<BQQ', 1, len(err:=msg.encode(... | 102 | 4,592 |
tinygrad | extra/hevc/hevc.py | .py | import dataclasses, enum, argparse, os, itertools, time, ctypes
from typing import Any
from tinygrad import Tensor, dtypes, Device, TinyJit
from tinygrad.helpers import DEBUG, round_up, ceildiv, Timing, prod
from tinygrad.runtime.autogen import avcodec, nv_570 as nv_gpu
class BitReader:
def __init__(self, data:bytes... | 451 | 22,175 |
tinygrad | extra/hevc/decode.py | .py | import argparse, os, hashlib, functools
from typing import Iterator, Callable
from tinygrad.helpers import getenv, DEBUG, round_up, Timing, tqdm, fetch, ceildiv
from extra.hevc.hevc import parse_hevc_file_headers, untile_nv12, to_bgr, nv_gpu
from tinygrad import Tensor, dtypes, Device, Variable, TinyJit
# rounds up he... | 105 | 5,375 |
tinygrad | extra/datasets/wikipedia_download.py | .py | # pip install gdown
# Downloads the 2020 wikipedia dataset used for MLPerf BERT training
import os, hashlib
from pathlib import Path
import tarfile
import gdown
from tqdm import tqdm
from tinygrad.helpers import getenv
def gdrive_download(url:str, path:str):
if not os.path.exists(path): gdown.download(url, path)
de... | 54 | 3,080 |
tinygrad | extra/datasets/squad.py | .py | import json
import os
from pathlib import Path
from transformers import BertTokenizer
import numpy as np
from tinygrad.helpers import fetch
BASEDIR = Path(__file__).parent / "squad"
def init_dataset():
os.makedirs(BASEDIR, exist_ok=True)
fetch("https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json", BAS... | 149 | 4,712 |
tinygrad | extra/datasets/preprocess_imagenet.py | .py | from tinygrad import Tensor, dtypes
from extra.datasets.imagenet import iterate, get_val_files
if __name__ == "__main__":
#sz = len(get_val_files())
sz = 32*100
X,Y = None, None
idx = 0
for x,y in iterate(shuffle=False):
print(x.shape, y.shape, x.dtype, y.dtype)
assert x.shape[0] == y.shape[0]
b... | 22 | 661 |
tinygrad | extra/datasets/imagenet_download.py | .py | # Python version of https://gist.github.com/antoinebrl/7d00d5cb6c95ef194c737392ef7e476a
from tinygrad.helpers import fetch
from pathlib import Path
from tqdm import tqdm
import tarfile, os
def imagenet_extract(file, path, small=False):
with tarfile.open(name=file) as tar:
if small: # Show progressbar only for bi... | 52 | 3,240 |
tinygrad | extra/datasets/__init__.py | .py | import os, gzip, tarfile, pickle
import numpy as np
from tinygrad import Tensor, dtypes
from tinygrad.helpers import fetch
def fetch_mnist(tensors=False):
parse = lambda file: np.frombuffer(gzip.open(file).read(), dtype=np.uint8).copy()
BASE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" # http://ya... | 44 | 2,373 |
tinygrad | extra/datasets/wikipedia.py | .py | # Preprocessing of downloaded text from Wikipedia for MLPerf BERT training
# This is a modified version of the original script:
# https://github.com/mlcommons/training/blob/master/language_model/tensorflow/bert/cleanup_scripts/create_pretraining_data.py
# ENV VARS:
# MAX_SEQ_LENGTH - Maximum sequence length
# ... | 399 | 14,457 |
tinygrad | extra/datasets/librispeech.py | .py | import json
import pathlib
import numpy as np
import librosa
import soundfile
"""
The dataset has to be downloaded manually from https://www.openslr.org/12/ and put in `extra/datasets/librispeech`.
For mlperf validation the dev-clean dataset is used.
Then all the flacs have to be converted to wav using something like... | 83 | 2,894 |
tinygrad | extra/datasets/imagenet.py | .py | # for imagenet download prepare.sh and run it
import glob, random, json, math
import numpy as np
from PIL import Image
import functools, pathlib
from tinygrad.helpers import diskcache, getenv
@functools.cache
def get_imagenet_categories():
ci = json.load(open(BASEDIR / "imagenet_class_index.json"))
return {v[0]: i... | 92 | 3,038 |
tinygrad | extra/datasets/fake_imagenet_from_mnist.py | .py | #!/usr/bin/env python3
import pathlib, json
from tinygrad.helpers import trange
from extra.datasets import fetch_mnist
from PIL import Image
import numpy as np
from multiprocessing import Pool
X_train, Y_train, X_test, Y_test = fetch_mnist()
def act(arg):
(basedir, i, train) = arg
if train:
img = np.uint8(X_t... | 41 | 1,305 |
tinygrad | extra/datasets/kits19.py | .py | import random
import functools
from pathlib import Path
import numpy as np
import nibabel as nib
from scipy import signal, ndimage
import os
import torch
import torch.nn.functional as F
from tqdm import tqdm
from tinygrad.tensor import Tensor
from tinygrad.helpers import fetch
BASEDIR = Path(__file__).parent / "kits19... | 220 | 10,161 |
tinygrad | extra/datasets/openimages.py | .py | import glob
import sys
import json
import numpy as np
from PIL import Image
from pathlib import Path
import boto3, botocore
from tinygrad import Tensor, dtypes
from tinygrad.helpers import fetch, tqdm, getenv
import pandas as pd
import concurrent.futures
BASEDIR = Path(__file__).parent / "open-images-v6-mlperf"
BUCKET... | 210 | 10,993 |
tinygrad | extra/sqtt/install_rocprof_decoder.py | .py | #!/usr/bin/env python3
import os, platform, shutil, subprocess
from pathlib import Path
from tinygrad.helpers import fetch, OSX
VERSION = "0.1.6"
DEST = Path("/usr/local/lib")
DEST.mkdir(exist_ok=True)
if __name__ == "__main__":
if OSX:
arch = "arm64" if platform.machine() == "arm64" else "x86_64"
dmg = fet... | 24 | 1,153 |
tinygrad | extra/sqtt/roc.py | .py | #!/usr/bin/env python3
import ctypes, pathlib, argparse, pickle, dataclasses, threading, itertools
from decimal import Decimal
from typing import Generator
from tinygrad.helpers import temp, unwrap, DEBUG
from tinygrad.runtime.ops_amd import ProfileSQTTEvent
from tinygrad.runtime.autogen import rocprof
from tinygrad.re... | 242 | 11,698 |
tinygrad | extra/sqtt/rgptool.py | .py | #!/usr/bin/env python3
from __future__ import annotations
import argparse, ctypes, struct, hashlib, pickle, code, typing, functools
import tinygrad.runtime.autogen.sqtt as sqtt
from tinygrad.device import ProfileEvent, ProfileDeviceEvent, ProfileProgramEvent
from tinygrad.runtime.ops_amd import ProfileSQTTEvent
from ti... | 348 | 18,417 |
tinygrad | extra/sqtt/examples/generate_examples.py | .py | import os, subprocess, sys, shlex
from pathlib import Path
from tinygrad.helpers import temp, getenv
EXAMPLES_DIR = Path(__file__).parent
PROFILE_PATH = Path(temp("profile.pkl", append_user=True))
EXAMPLES = {
"empty":"test/backend/test_custom_kernel.py TestCustomKernel.test_empty",
"plus":"test/test_tiny.py Test... | 28 | 1,392 |
tinygrad | extra/viz/kernel_graph.py | .py | #!/usr/bin/env python3
# Usage: DEBUG=5 python -m tinygrad.viz.cli --json | ./extra/viz/kernel_graph.py > /tmp/kernel_graph.txt
import argparse, json, sys, itertools
from tinygrad.helpers import ansistrip
from tinygrad.viz.cli import fmt_all
def get_node(graph:dict, key): return graph[str(key)]
if __name__ == "__main... | 48 | 2,329 |
tinygrad | extra/usbgpu/scan_pci.py | .py | import array, time
from hexdump import hexdump
from tinygrad.runtime.support.usb import ASM24Controller
from tinygrad.runtime.autogen import pci
usb = ASM24Controller()
def print_cfg(bus, dev):
cfg = []
for i in range(0, 256, 4):
cfg.append(usb.pcie_cfg_req(i, bus=bus, dev=dev, fn=0, value=None, size=4))
p... | 68 | 2,844 |
tinygrad | extra/usbgpu/debug.py | .py | #!/usr/bin/env python3
import sys
import time
from argparse import ArgumentParser
from pyftdi.ftdi import Ftdi
from pyftdi.eeprom import FtdiEeprom
from pyftdi.misc import hexdump
class USBGPUDebug:
CBUS_RESET = (1 << 2)
CBUS_BOOTLOADER = (1 << 1)
def __init__(self, device_url: str = 'ftdi://ftdi:230x/1'):
... | 103 | 3,198 |
tinygrad | extra/usbgpu/patch.py | .py | #!/usr/bin/env python3
import os, zlib, struct, hashlib
from tinygrad.helpers import getenv
from tinygrad.runtime.support.usb import USB3
SUPPORTED_CONTROLLERS = [
(0x174C, 0x2464),
(0x174C, 0x2463),
(0xADD1, 0x0001),
]
if getenv("USBDEV", ""): SUPPORTED_CONTROLLERS.insert(0, (int(x, 16) for x in getenv("USBDEV"... | 99 | 4,458 |
tinygrad | extra/usbgpu/legacy/wr_speed.py | .py | import array, time, ctypes, struct, random
from hexdump import hexdump
from tinygrad.runtime.support.usb import ASMController, WriteOp
from tinygrad.runtime.autogen import pci
from tinygrad.helpers import Timing
from tinygrad import Device
usb = ASMController()
xxx = (ctypes.c_uint8 * 4096)()
dfg = random.randint(0, ... | 23 | 530 |
tinygrad | extra/usbgpu/legacy/nvme_speed.py | .py | import array, time, ctypes, struct, random
from hexdump import hexdump
from tinygrad.runtime.support.usb import ASM24Controller, WriteOp, ScsiWriteOp
from tinygrad.runtime.autogen import pci
from tinygrad.helpers import Timing
from tinygrad import Device
usb = ASM24Controller()
def real_scsi_write():
self.exec_ops(... | 24 | 688 |
tinygrad | extra/usbgpu/legacy/patch_exp.py | .py | #!/usr/bin/env python3
import sys
import zlib
def patch(input_filepath, output_filepath, patches):
with open(input_filepath, 'rb') as infile: data = bytearray(infile.read())
for offset, expected_bytes, new_bytes in patches:
if len(expected_bytes) != len(new_bytes):
print(len(expected_bytes), len(new_byt... | 89 | 4,096 |
tinygrad | extra/perfetto/to_perfetto.py | .py | import sys, pickle, decimal, json
from tinygrad.device import ProfileDeviceEvent, ProfileGraphEvent
from tinygrad.helpers import tqdm, temp, ProfileEvent, ProfileRangeEvent, TracingKey
devices:dict[str, tuple[decimal.Decimal, int]] = {}
def prep_ts(device:str, ts:decimal.Decimal): return int(decimal.Decimal(ts) + devi... | 42 | 2,480 |
tinygrad | extra/fp8/fp8_linear.py | .py | from typing import Callable, Any
from tinygrad import Tensor, dtypes, nn, UOp
from tinygrad.uop.ops import KernelInfo, AxisType, Ops
def quantize_to_fp8(x: Tensor, dtype=dtypes.fp8e4m3):
fp8_min = -448.0 if dtype == dtypes.fp8e4m3 else -57344.0
fp8_max = 448.0 if dtype == dtypes.fp8e4m3 else 57344.0
x_abs_max = ... | 102 | 5,203 |
tinygrad | extra/testsig/generate_testsig.py | .py | #!/usr/bin/env python3
"""
Self-contained Qualcomm Hexagon **testsig** generator.
Replicates: python2 elfsigner.py -t 0x67489311 -o .
Dependencies: standard library + cryptography (pip install cryptography).
Multiple serial numbers: use -t multiple times.
"""
import argparse, base64, hashlib, os, struct
from datetime... | 295 | 16,511 |
tinygrad | extra/hcq/hcq_smi.py | .py | #!/usr/bin/env python3
import argparse, glob, os, time, subprocess, sys
from tinygrad.helpers import temp
def scan_devs_based_on_lock(prefix:str, args) -> list[str]:
target_dev = args.pci_bus if 'pci_bus' in args.__dir__() else ""
devs = []
for dev in glob.glob(temp(f'{prefix}_*.lock')):
dev_id = dev.split... | 114 | 4,559 |
tinygrad | extra/optimization/extract_dataset.py | .py | #!/usr/bin/env python3
# extract asts from process replay artifacts
import os
from test.external.process_replay.process_replay import _pmap
LOGOPS = os.getenv("LOGOPS", "/tmp/sops")
def extract_ast(*args) -> None:
open(LOGOPS, "a").write(str(args[1]).replace("\n", "").replace(" ", "")+"\n")
return None
if __name... | 14 | 377 |
tinygrad | extra/optimization/test_beam_search.py | .py | import unittest
import numpy as np
from tinygrad.helpers import BEAM, Timing, prod
from tinygrad import Variable, Device, Tensor
from tinygrad.nn import Conv2d
from tinygrad.uop.ops import AxisType, Ops
from tinygrad.codegen.opt import Opt, OptOps
from tinygrad.codegen.opt.postrange import Scheduler
from tinygrad.code... | 106 | 4,027 |
tinygrad | extra/hcq2/ops_amd2.py | .py | from __future__ import annotations
from typing import cast, Any, Callable
import os, ctypes, struct, hashlib, functools, importlib, mmap, errno, array, contextlib, sys, weakref, itertools, collections, atexit
assert sys.platform != 'win32'
from dataclasses import dataclass
from tinygrad.runtime.support.hcq2 import HCQ2... | 722 | 45,273 |
tinygrad | extra/torch_hook/hook_cuda.py | .py | import ctypes, struct, platform, pathlib, os, binascii, itertools
from hexdump import hexdump
from tinygrad.helpers import to_mv, DEBUG, getenv, colored, time_to_str
from tinygrad.runtime.autogen import libc, cuda
from tinygrad.device import CPUProgram, Device
from tinygrad.runtime.support.elf import elf_loader
from ti... | 215 | 8,977 |
tinygrad | extra/torch_hook/hook_torch.py | .py | import ctypes, struct, platform, pathlib, os, binascii, itertools
from hexdump import hexdump
from tinygrad.device import Device
from tinygrad import Tensor
from tinygrad.dtype import _from_torch_dtype
from tinygrad.helpers import to_mv, DEBUG, getenv, colored, time_to_str
import extra.torch_hook.hook_cuda as hook_cud... | 151 | 5,923 |
tinygrad | extra/nv_gpu_driver/nv_ioctl.py | .py | # type: ignore
import ctypes, ctypes.util, struct, platform, pathlib, re, time, os, signal
from tinygrad.helpers import from_mv, to_mv, getenv
from tinygrad.runtime.support.c import init_c_struct_t
from hexdump import hexdump
start = time.perf_counter()
# *** ioctl lib ***
libc = ctypes.CDLL(ctypes.util.find_library("... | 367 | 19,616 |
tinygrad | extra/models/retinanet.py | .py | import math
from tinygrad import Tensor, dtypes
from tinygrad.helpers import flatten, get_child, TRAINING
from examples.mlperf.helpers import generate_anchors, BoxCoder
from examples.mlperf.losses import sigmoid_focal_loss, l1_loss
from extra.models.resnet import ResNet
import tinygrad.nn as nn
import numpy as np
Conv... | 264 | 12,629 |
tinygrad | extra/models/bert.py | .py | import re, os
from pathlib import Path
from tinygrad.tensor import Tensor, cast
from tinygrad import nn, dtypes
from tinygrad.helpers import fetch, get_child
from tinygrad.nn.state import get_parameters
# allow for monkeypatching
Embedding = nn.Embedding
Linear = nn.Linear
LayerNorm = nn.LayerNorm
class BertForQuesti... | 301 | 14,747 |
tinygrad | extra/models/unet.py | .py | from tinygrad import Tensor, Device, dtypes, nn
from typing import Optional, Union, List, Any, Tuple, Callable
import math
# allow for monkeypatching
Linear, Conv2d, GroupNorm, LayerNorm = nn.Linear, nn.Conv2d, nn.GroupNorm, nn.LayerNorm
attention, gelu, mixed_precision_dtype = Tensor.scaled_dot_product_attention, Ten... | 263 | 10,178 |
tinygrad | extra/models/transformer.py | .py | from tinygrad import Tensor
class TransformerBlock:
def __init__(self, embed_dim, num_heads, ff_dim, prenorm=False, act=lambda x: x.relu(), dropout=0.1):
assert embed_dim % num_heads == 0, "embed_dim must be divisible by num_heads"
self.num_heads = num_heads
self.head_size = embed_dim // num_heads
s... | 62 | 2,775 |
tinygrad | extra/models/clip.py | .py | from tinygrad import Tensor, dtypes
from tinygrad.helpers import fetch
from tinygrad.nn import Linear, LayerNorm, Embedding, Conv2d
from typing import List, Optional, Union, Tuple, Dict
from abc import ABC, abstractmethod
from functools import lru_cache
import numpy as np
import re, gzip
# Allow for monkeypatching fo... | 481 | 19,141 |
tinygrad | extra/models/resnet.py | .py | import tinygrad.nn as nn
from tinygrad import Tensor, dtypes
from tinygrad.nn.state import torch_load
from tinygrad.helpers import fetch, get_child
# allow monkeypatching in layer implementations
BatchNorm = nn.BatchNorm2d
Conv2d = nn.Conv2d
Linear = nn.Linear
class BasicBlock:
expansion = 1
def __init__(self, ... | 171 | 6,770 |
tinygrad | extra/models/convnext.py | .py | from tinygrad.tensor import Tensor
from tinygrad.nn import Conv2d, LayerNorm, LayerNorm2d, Linear
from tinygrad.helpers import fetch, get_child, Context
class Block:
def __init__(self, dim):
self.dwconv = Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
self.norm = LayerNorm(dim, eps=1e-6)
self.pwc... | 64 | 2,489 |
tinygrad | extra/models/unet3d.py | .py | from pathlib import Path
import torch
from tinygrad import nn
from tinygrad.tensor import Tensor
from tinygrad.helpers import fetch, get_child
class DownsampleBlock:
def __init__(self, c0, c1, stride=2):
self.conv1 = [nn.Conv2d(c0, c1, kernel_size=(3,3,3), stride=stride, padding=(1,1,1,1,1,1), bias=False), nn.In... | 60 | 2,504 |
tinygrad | extra/models/mask_rcnn.py | .py | import re
import math
import os
import numpy as np
from pathlib import Path
from tinygrad import nn, Tensor, dtypes
from tinygrad.tensor import _to_np_dtype
from tinygrad.helpers import get_child, fetch, TRAINING
from tinygrad.nn.state import torch_load
from examples.mlperf.helpers import BoxCoder
from extra.models.res... | 1,215 | 39,423 |
tinygrad | extra/models/llama.py | .py | from typing import Union, Optional, Any
import collections, math
from tinygrad import Tensor, Variable, TinyJit, dtypes, nn, Device
from tinygrad.helpers import getenv, DEBUG
# https://github.com/facebookresearch/llama/blob/1076b9c51c77ad06e9d7ba8a4c6df775741732bd/llama/model.py#L47
def precompute_freqs_cis(dim: int, ... | 287 | 15,329 |
tinygrad | extra/models/rnnt.py | .py | from tinygrad.tensor import Tensor
from tinygrad.engine.jit import TinyJit
from tinygrad.nn import Linear, Embedding
from tinygrad.helpers import fetch
import numpy as np
from pathlib import Path
class RNNT:
def __init__(self, input_features=240, vocab_size=29, enc_hidden_size=1024, pred_hidden_size=320, joint_hidd... | 203 | 7,938 |
tinygrad | extra/models/t5.py | .py | # pip3 install sentencepiece
# adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py
# coding=utf-8
# Copyright 2018 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not u... | 286 | 12,091 |
tinygrad | extra/models/vit.py | .py | import numpy as np
from tinygrad.tensor import Tensor
from tinygrad.helpers import fetch
from extra.models.transformer import TransformerBlock
class ViT:
def __init__(self, layers=12, embed_dim=192, num_heads=3):
self.embedding = (Tensor.uniform(embed_dim, 3, 16, 16), Tensor.zeros(embed_dim))
self.embed_dim ... | 74 | 4,170 |
tinygrad | extra/models/inception.py | .py | from tinygrad import Tensor
from tinygrad.nn import Conv2d, BatchNorm2d, Linear
from tinygrad.nn.state import load_state_dict, torch_load
from tinygrad.helpers import fetch
from typing import Optional, Dict
import numpy as np
from scipy import linalg
# Base Inception Model
class BasicConv2d:
def __init__(self, in_... | 345 | 13,404 |
tinygrad | extra/models/efficientnet.py | .py | import math
from tinygrad.tensor import Tensor
from tinygrad.nn import BatchNorm2d
from tinygrad.helpers import get_child, fetch
from tinygrad.nn.state import torch_load
class MBConvBlock:
def __init__(self, kernel_size, strides, expand_ratio, input_filters, output_filters, se_ratio, has_se, track_running_stats=True... | 165 | 6,792 |
tinygrad | extra/hcqfuzz/fuzzer.py | .py | import os, random, subprocess, shlex, datetime, time, signal
from extra.hcqfuzz.tools import create_report, on_start_run, collect_tests, init_log, log
from extra.hcqfuzz.spec import AMSpec
def run_test(dev, test):
on_start_run(dev, test)
dev_env = dev.get_exec_state()
test_env, cmd, timeout = test.get_exec_stat... | 73 | 2,293 |
tinygrad | extra/hcqfuzz/spec.py | .py | import os, random
class TestSpec:
def prepare(self, device, seed):
raise NotImplementedError("prepare must be implemented in the derived class")
def get_exec_state(self):
raise NotImplementedError("get_exec_state must be implemented in the derived class")
def name(self): return self.__class__.__name__
c... | 43 | 1,326 |
tinygrad | extra/hcqfuzz/tools.py | .py | import pickle, datetime, os, tempfile, subprocess, zipfile, importlib.util
from extra.hcqfuzz.spec import TestSpec
from tinygrad.helpers import getenv
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_DIR = os.path.join(BASE_DIR, "tests")
REPORTS_DIR = os.path.join(BASE_DIR, "reports")
def collect_tests():
... | 81 | 2,925 |
tinygrad | extra/hcqfuzz/tests/bert.py | .py | from extra.hcqfuzz.spec import TestSpec
import random
bert_train_params = {
"DEFAULT_FLOAT": "HALF",
"SUM_DTYPE": "HALF",
"GPUS": 6,
"BS": 96,
"EVAL_BS": 96,
"BASEDIR": "/raid/datasets/wiki",
}
class TrainBert(TestSpec):
def prepare(self, dev, seed):
random.seed(seed)
self.env = {
**bert_... | 82 | 1,954 |
tinygrad | extra/hcqfuzz/tests/allocator.py | .py | from extra.hcqfuzz.spec import TestSpec
import random
class TLSFAllocator(TestSpec):
def prepare(self, dev, seed):
random.seed(seed)
self.env = {
"SEED": seed,
"ITERS": random.randint(10000, 1000000),
}
self.cmd = "python3 test/external/external_fuzz_tlsf.py"
self.timeout = 60 *... | 17 | 406 |
tinygrad | extra/hcqfuzz/tests/resnet.py | .py | from extra.hcqfuzz.spec import TestSpec
import random
resnet_train_params = {
"DEFAULT_FLOAT": "HALF",
"SUM_DTYPE": "HALF",
"GPUS": 6,
"BS": 1536,
"EVAL_BS": 192,
"TRAIN_BEAM": 4,
"IGNORE_JIT_FIRST_BEAM": 1,
"BEAM_UOPS_MAX": 2000,
"BEAM_UPCAST_MAX": 96,
"BEAM_LOCAL_MAX": 1024,
"BEAM_MIN_PROGRESS"... | 67 | 1,487 |
tinygrad | extra/hcqfuzz/tests/hcq.py | .py | from extra.hcqfuzz.spec import TestSpec
import random
class HCQSignalFuzzer(TestSpec):
def prepare(self, dev, seed):
random.seed(seed)
self.env = {
"GPUS": random.choice([2, 3, 4, 5, 6]),
"ITERS": random.randint(1000000, 10000000),
"SEED": seed,
}
self.cmd = "python3 test/external... | 36 | 1,043 |
tinygrad | extra/hcqfuzz/tests/allreduce.py | .py | from extra.hcqfuzz.spec import TestSpec
import random
class RingAllreduce(TestSpec):
def prepare(self, dev, seed):
random.seed(seed)
self.env = {
"GPUS": random.choice([2, 3, 4, 5, 6]),
"ITERS": random.randint(10, 1000),
"DEBUG": 2,
}
self.cmd = "python3 test/external/external_ben... | 18 | 462 |
tinygrad | extra/tinyfs/fetch_file.py | .py | from tinygrad.tensor import Tensor
from tinygrad.helpers import CHUNK_SIZE
from tinygrad.nn.state import fs_load
import argparse, math, hashlib
def _python_hash_1mb(data:bytes|bytearray):
chunks = [data[i:i+4096] for i in range(0, len(data), 4096)]
chunk_hashes = [hashlib.shake_128(chunk).digest(16) for chunk in c... | 39 | 1,747 |
tinygrad | extra/tinyfs/fetch_raid.py | .py | import json, multiprocessing, functools
from pathlib import Path
from tinygrad.tensor import Tensor
from tinygrad.helpers import tqdm, getenv
from tinygrad.nn.state import fs_load
raid_root = Path(getenv("RAID_ROOT", "/raid"))
def fetch_file(item):
path, info = item
h, size = info["hash"], info["size"]
path =... | 43 | 1,337 |
tinygrad | extra/tinyfs/upload_raid.py | .py | from pathlib import Path
import multiprocessing, json
from tinygrad.tensor import Tensor
from tinygrad.helpers import tqdm
from tinygrad.nn.state import fs_store
raid_root = Path("/raid")
def upload_file(path: Path):
pt = Tensor(path).realize()
h = fs_store(pt).realize()
pt.uop.realized.deallocate()
return h... | 33 | 1,033 |
tinygrad | extra/gemm/triton_nv_matmul.py | .py | import time
import triton
import triton.language as tl
from triton.compiler import AttrsDescriptor, ASTSource, compile as triton_compile
import numpy as np
from tinygrad import Tensor, dtypes, Device
from tinygrad.engine.realize import get_runtime
from tinygrad.codegen import to_program
from tinygrad.uop.ops import Ops... | 118 | 4,773 |
tinygrad | extra/gemm/cuda_matmul.py | .py | import os
import numpy as np
os.environ["CUDA"] = "1"
from tinygrad.runtime.ops_cuda import CUDAAllocator, CUDADevice, CUDAProgram, CUDACompiler
from tinygrad.helpers import flat_mv
FLOAT16 = True
ACC_FLOAT16 = False
N = 4096
na = np.random.default_rng().standard_normal(size=(N,N), dtype=np.float32)
nb = np.random.de... | 107 | 4,052 |
tinygrad | extra/gemm/moe_routing.py | .py | from tinygrad import Tensor, dtypes
from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType
BLOCK_ROW = 256
def _sharded_invalids(shape:tuple[int, ...], dtype, device) -> Tensor:
if isinstance(device, tuple):
per = Tensor.invalids(shape[0]//len(device), *shape[1:], dtype=dtype, device=device)
return Ten... | 132 | 5,965 |
tinygrad | extra/gemm/cdna_asm_gemm.py | .py | import atexit, functools, math, pathlib
from tinygrad import Tensor, Device, dtypes
from tinygrad.dtype import AddrSpace
from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType
from tinygrad.renderer import Estimates
from tinygrad.helpers import getenv, all_same, DEBUG, ceildiv
from tinygrad.runtime.support.compile... | 480 | 28,678 |
tinygrad | extra/gemm/metal_uop_matmul.py | .py | from tinygrad import UOp, dtypes
from tinygrad.uop.ops import AxisType, KernelInfo, AddrSpace
from extra.gemm.amd_uop_matmul import test_matmul
N = 2048
# metal has an 8x8 tensor core. this is the indexing
def mat_idx(buf, g0, g1, warp, u):
l = [(warp//2**i)%2 for i in range(5)]
return buf[g0, l[4]*4 + l[2]*2 + l... | 40 | 1,500 |
tinygrad | extra/gemm/simple_matmul.py | .py | import numpy as np
from tinygrad import dtypes, Tensor
from tinygrad.helpers import getenv, get_single_element
from tinygrad.dtype import _to_np_dtype
from tinygrad.engine.realize import compile_linear
from tinygrad.codegen.opt import OptOps
dtype_in = (dtypes.half if getenv("HALF") else dtypes.bfloat16 if getenv("BFL... | 58 | 2,553 |
tinygrad | extra/gemm/max_matmul.py | .py | import numpy as np, os
from tinygrad.helpers import getenv, flat_mv
from tinygrad import dtypes
# for copied uops
from tinygrad import dtypes
from tinygrad.dtype import DTYPES_DICT
script_dir = os.path.dirname(os.path.abspath(__file__))
# problem variations
DTYPE_IN = DTYPES_DICT[getenv("DTYPE_IN", "half")]
DTYPE_OU... | 219 | 11,375 |
tinygrad | extra/gemm/mi350x_uop_matmul.py | .py | import os
import numpy as np
np.set_printoptions(linewidth=1000000)
os.environ["AMD_LLVM"] = "0"
from tinygrad import Tensor, Context, dtypes, UOp, GlobalCounters
from tinygrad.helpers import DEBUG, getenv
from tinygrad.dtype import AddrSpace
from tinygrad.uop.ops import AxisType, KernelInfo
WARP_SIZE = 64
# Reg til... | 228 | 9,094 |
tinygrad | extra/gemm/gemm.py | .py | #!/usr/bin/env python3
import os
#os.environ['OMP_NUM_THREADS'] = '1'
import time
import numpy as np
N = 512
if __name__ == "__main__":
# N^2
A = np.random.randn(N, N).astype(np.float32)
# N^2
B = np.random.randn(N, N).astype(np.float32)
# 2N compute in N^2 output cells
flop = 2*N*N*N
#print(f"{flop / 1... | 29 | 599 |
tinygrad | extra/gemm/gemm_mxfp4.py | .py | # ruff: noqa: E501,F403,F405
from tinygrad.runtime.autogen.amd.cdna.ins import *
class Kernel:
def __init__(self): self.instructions, self.labels, self.pos = [], {}, 0
def label(self, name): self.labels[name] = self.pos
def emit(self, inst, target=None):
self.instructions.append(inst)
inst._target, inst.... | 4,125 | 254,735 |
tinygrad | extra/gemm/halide_gemm.py | .py | import numpy as np
import halide as hl
from tinygrad.helpers import Timing, getenv
# HL_DEBUG_CODEGEN=1
N = getenv("N", 1024)
def gemm_pipeline(gpu=False):
# ---------------- Vars & Parameters ----------------
i, j = hl.Var("i"), hl.Var("j") # output tile coordinates
A = hl.InputBuffer(hl.Float(32), 2) # [M,... | 91 | 2,464 |
tinygrad | extra/gemm/amd_asm_matmul.py | .py | # RDNA3 128x128 tiled GEMM kernel - DSL version
# Computes C = A @ B for NxN float32 matrices using 128x128 tiles
#
# Architecture: RDNA3 (gfx1100)
# Tile size: 128x128 (each workgroup computes one tile of C)
# Workgroup: 128 threads (arranged as 32x4 for coalesced memory access)
# Inner loop: 8 iterations per K-block,... | 502 | 24,908 |
tinygrad | extra/gemm/amd_uop_matmul.py | .py | from tinygrad import Tensor, Context, GlobalCounters, dtypes
from tinygrad.uop.ops import UOp, KernelInfo, sint, AxisType
from tinygrad.dtype import AddrSpace
from tinygrad.helpers import DEBUG, getenv
N = getenv("N", 4096)
M = getenv("M", N)
K = getenv("K", N)
NUM_RUNS = getenv("CNT", 5)
# --------------------------... | 143 | 6,328 |
tinygrad | extra/gemm/tvm_gemm.py | .py | # https://tvm.apache.org/docs/tutorial/tensor_expr_get_started.html#example-2-manually-optimizing-matrix-multiplication-with-te
M, N, K = 1024, 1024, 1024
try:
import tvm
from tvm import te
#print(tvm.target.Target.list_kinds())
# c, opencl
target = tvm.target.Target(target="c")
# TVM Matrix Multiplicat... | 47 | 1,362 |
tinygrad | extra/gemm/simple_matvec.py | .py | import numpy as np
from tinygrad.helpers import getenv
from tinygrad import dtypes, Tensor, Device
dtype_in = dtypes.half if getenv("HALF") else dtypes.bfloat16 if getenv("BFLOAT16") else dtypes.float
acc_dtype = dtypes.half if getenv("ACC_HALF") else dtypes.bfloat16 if getenv("ACC_BFLOAT16") else None
GPUS = getenv("... | 31 | 1,105 |
tinygrad | extra/gemm/rdna4_asm_matmul.py | .py | # RDNA4 128x128 GEMM using WMMA — optimized DS scheduling
import numpy as np
from tinygrad import Tensor, Device, Context, GlobalCounters
from tinygrad.uop.ops import UOp, Ops, KernelInfo
from tinygrad.helpers import getenv, colored
from tinygrad.dtype import dtypes, AddrSpace
from tinygrad.engine.realize import Estima... | 250 | 12,215 |
tinygrad | extra/gemm/metal_conv.py | .py | import os
#os.environ["METAL"] = "1"
import numpy as np
BS = 64
CIN = 256
COUT = 256
HW = 32
K = 3
PADDING = 0
# TODO: this is doing some trick, since with CIN=256 COUT=256 it's over 10.4 TFLOPS.
# are winograd convs less flops? it appears so if they are batched
# https://www.cse.ust.hk/~weiwa/papers/yan-ppopp20.pdf
F... | 50 | 1,550 |
tinygrad | extra/gemm/real_pmatmul.py | .py | import time
from tinygrad import Tensor, Device, TinyJit
from tinygrad.helpers import getenv
if __name__ == "__main__":
DEVS = [f"NV:{i}" for i in range(getenv("GPUS", 2))]
N = getenv("N", 8192)
A = Tensor.rand(N, N).shard(DEVS, 0).realize()
B = Tensor.rand(N, N).shard(DEVS, 1).realize()
print("***** MUL ***... | 21 | 638 |
tinygrad | extra/gemm/metal_matvec.py | .py | import numpy as np
import time, torch, torch.mps
from tinygrad import Tensor, TinyJit, Device
from tinygrad.helpers import flat_mv
from tinygrad.runtime.ops_metal import MetalAllocator, MetalDevice, MetalProgram, MetalCompiler
N = 16384
M = 4096
FLOPS = N*M*2
nb = np.random.default_rng().standard_normal(size=(N), dt... | 113 | 5,060 |
tinygrad | extra/gemm/tinygrad_nv_matmul.py | .py | from tinygrad import Tensor, dtypes, Context
from tinygrad.helpers import getenv
from tinygrad.codegen.opt import Opt, OptOps
from tinygrad.engine.realize import run_linear
from dataclasses import replace
N = 4096
if __name__ == "__main__":
if getenv("GEMV"):
A, B = Tensor.empty(1, N, dtype=dtypes.float), Tensor... | 35 | 1,247 |
tinygrad | extra/gemm/simple_conv.py | .py | from tinygrad.helpers import getenv
from tinygrad import dtypes, Tensor
dtype_in = dtypes.half if getenv("HALF") else dtypes.bfloat16 if getenv("BFLOAT16") else dtypes.float
acc_dtype = dtypes.half if getenv("ACC_HALF") else dtypes.bfloat16 if getenv("ACC_BFLOAT16") else None
CNT = getenv("CNT", 8)
BS = getenv("BS", ... | 34 | 1,291 |
tinygrad | extra/gemm/metal_matmul.py | .py | import os
os.environ["METAL"] = "1"
import time
import numpy as np
from tinygrad import Device, dtypes
from tinygrad.helpers import getenv, flat_mv
from tinygrad.runtime.ops_metal import MetalAllocator, MetalDevice, MetalProgram, MetalCompiler
N = getenv("N", 2048)
LID = 2
device = MetalDevice("METAL")
metalalloc = M... | 133 | 5,586 |
tinygrad | extra/gemm/hip_matmul.py | .py | import time
import numpy as np
from tinygrad.helpers import getenv, prod, flat_mv
from tinygrad.runtime.ops_amd import AMDAllocator, AMDDevice, AMDProgram
# AMD_LOG_LEVEL=3 ./MIOpenDriver gemm --iter 1000 --time 1 --a_w 2048 --a_h 2048 --b_w 2048
# 5.5: Cijk_Ailk_Bljk_HHS_BH_MT128x128x16_MI16x16x16x1_SN_1LDSB0_APM1_AB... | 143 | 6,348 |
tinygrad | extra/gemm/amd_matmul.py | .py | # kernel8_batched_gmem.s from https://seb-v.github.io/optimization/update/2025/01/20/Fast-GPU-Matrix-multiplication.html
# sudo PATH=/opt/homebrew/Cellar/llvm/20.1.6/bin:$PATH AMD_LLVM=0 AMD=1 DEBUG=2 python3 extra/gemm/amd_matmul.py
import pathlib
from tinygrad import Tensor, Device, Context, GlobalCounters
from tinyg... | 51 | 2,253 |
tinygrad | extra/gemm/moe_gemm.py | .py | import functools, pathlib
from tinygrad import Tensor, dtypes
from tinygrad.uop.ops import UOp, Ops, KernelInfo
from tinygrad.renderer import Estimates
from tinygrad.runtime.support.compiler_amd import HIPCCCompiler
from extra.gemm.cdna_asm_gemm import quantize_mxfp8, _mx_block_scale, _mx_block_scale_3d
@functools.cac... | 112 | 6,675 |
tinygrad | extra/gemm/amd_copy_matmul.py | .py | from tinygrad import Device, UOp, getenv
from tinygrad.uop.ops import AxisType, KernelInfo
from tinygrad.dtype import AddrSpace, dtypes
N = getenv("N", 4096)
M = getenv("M", N)
K = getenv("K", N)
WARP_SIZE = 32
BLOCK_M, BLOCK_N = 128, 128
BLOCK_K = getenv("BK", 16)
assert N % BLOCK_N == 0 and M % BLOCK_M == 0 and K %... | 119 | 5,438 |
tinygrad | extra/gemm/mi350x_uop_matmul_2.py | .py | import os
import numpy as np
np.set_printoptions(linewidth=1000000)
os.environ["AMD_LLVM"] = "0"
from tinygrad import Tensor, Context, dtypes, UOp, GlobalCounters
from tinygrad.helpers import DEBUG, getenv
from tinygrad.dtype import AddrSpace
from tinygrad.uop.ops import AxisType, KernelInfo
WARP_SIZE = 64
# Reg til... | 141 | 5,459 |
tinygrad | extra/gemm/torch_gemm.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"
import time
import torch
torch.set_num_threads(1)
from tinygrad.helpers import getenv
CUDA = getenv("CUDA", 1)
MPS = getenv("MPS", 0)
if getenv("FP16_ACC"): ... | 31 | 1,059 |
tinygrad | extra/gemm/fuzz_matmul.py | .py | import numpy as np
from tinygrad.helpers import getenv
from tinygrad import dtypes, Tensor
dtype_in = dtypes.half if getenv("HALF") else dtypes.bfloat16 if getenv("BFLOAT16") else dtypes.float
acc_dtype = dtypes.half if getenv("ACC_HALF") else dtypes.bfloat16 if getenv("ACC_BFLOAT16") else None
N_START = getenv("N_STAR... | 44 | 1,822 |
tinygrad | extra/torch_backend/example.py | .py | from PIL import Image
from tinygrad.helpers import getenv, GlobalCounters
import torch, torchvision, pathlib, warnings
import torchvision.transforms as transforms
import extra.torch_backend.backend
device = "tiny"
torch.set_default_device(device)
if __name__ == "__main__":
GlobalCounters.reset()
img = Image.open(p... | 31 | 1,336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.