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
scientific-agent-skills
skills/relsa-severity-assessment/scripts/_common.py
.py
"""Shared I/O, validation, and variable-preparation helpers for the RELSA workflow. The RELSA long format is one row per animal per time point: id treatment condition time var_1 ... var_n ``id`` and ``time`` are required; ``treatment`` and ``condition`` are optional grouping labels carried through untouc...
288
11,359
scientific-agent-skills
skills/relsa-severity-assessment/scripts/kde_thresholds.py
.py
#!/usr/bin/env python3 """Kernel-density thresholds on the RELSA scale (severity zones). Lutscher et al. (2026) define candidate severity thresholds by estimating the probability density of the RELSA scores observed in a model and taking the *minima* of that density β€” the sparsely populated valleys between clusters of...
370
14,420
scientific-agent-skills
skills/relsa-severity-assessment/scripts/relsa_score.py
.py
#!/usr/bin/env python3 """RELSA (RELative Severity Assessment) score β€” a faithful Python port. Implements the four-step procedure of Talbot et al. (2022), Front. Vet. Sci. 9:937711, as coded in the R package ``mytalbot/RELSA``: 1. directionality β€” variables that *rise* under duress are "turned"; 2. normalization β€” ea...
489
18,887
scientific-agent-skills
skills/pathway-enrichment/scripts/run_enrichment.py
.py
#!/usr/bin/env python3 """Run over-representation (ORA) or preranked GSEA with gseapy. Handles the boilerplate that every enrichment run repeats: symbol cleanup, deduplication, NA removal, building a ranking metric from a DESeq2 table, per-library FDR filtering, and a dotplot. Outputs a combined results CSV and a dotp...
232
8,550
scientific-agent-skills
skills/neurokit2/scripts/generate_synthetic.py
.py
#!/usr/bin/env python3 """Generate deterministic, dependency-free synthetic biosignal CSV fixtures.""" from __future__ import annotations import argparse import math import random from collections.abc import Sequence from typing import Any from _common import ( MAX_ROWS, CliError, emit_json, finite_f...
222
7,584
scientific-agent-skills
skills/neurokit2/scripts/_common.py
.py
#!/usr/bin/env python3 """Shared bounded, local-only helpers for the NeuroKit2 skill CLIs.""" from __future__ import annotations import csv import hashlib import io import json import math import os import stat import tempfile from collections.abc import Iterable, Mapping, Sequence from pathlib import Path from typin...
568
18,958
scientific-agent-skills
skills/neurokit2/scripts/eda_pipeline.py
.py
#!/usr/bin/env python3 """Run an explicit, bounded EDA cleaning/decomposition/SCR workflow.""" from __future__ import annotations import argparse import statistics from typing import Any from _common import ( MAX_CSV_BYTES, MAX_ROWS, NEUROKIT2_VERSION, PINNED_INSTALL, CliError, checked_input_...
289
9,986
scientific-agent-skills
skills/neurokit2/scripts/inspect_signal.py
.py
#!/usr/bin/env python3 """Inspect bounded local biosignal CSV structure without exposing row values.""" from __future__ import annotations import argparse import csv import math import statistics from pathlib import Path from typing import Any from _common import ( MAX_CELL_CHARS, MAX_CHANNELS, MAX_CSV_B...
363
13,519
scientific-agent-skills
skills/neurokit2/scripts/validate_multimodal.py
.py
#!/usr/bin/env python3 """Validate bounded multimodal stream schemas and temporal alignment.""" from __future__ import annotations import argparse import math import re import statistics from itertools import pairwise from pathlib import Path from typing import Any from _common import ( MAX_CSV_BYTES, MAX_RO...
351
12,505
scientific-agent-skills
skills/neurokit2/scripts/ecg_hrv_pipeline.py
.py
#!/usr/bin/env python3 """Run a bounded ECG processing and duration-aware HRV workflow.""" from __future__ import annotations import argparse from typing import Any from _common import ( MAX_CSV_BYTES, MAX_ROWS, NEUROKIT2_VERSION, PINNED_INSTALL, CliError, checked_input_file, dataframe_ro...
304
10,917
scientific-agent-skills
skills/neurokit2/scripts/plan_epochs.py
.py
#!/usr/bin/env python3 """Plan sample-exact event epochs without loading NeuroKit2.""" from __future__ import annotations import argparse import math from typing import Any from _common import ( MAX_CSV_BYTES, MAX_ROWS, CliError, checked_input_file, emit_json, finite_float, read_numeric_c...
282
10,040
scientific-agent-skills
skills/pytorch-lightning/scripts/template_lightning_module.py
.py
""" Template for creating a PyTorch Lightning Module. This template provides a complete boilerplate for building a LightningModule with all essential methods and best practices. """ import lightning as L import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam from torch.optim.l...
221
6,045
scientific-agent-skills
skills/pytorch-lightning/scripts/template_datamodule.py
.py
""" Template for creating a PyTorch Lightning DataModule. This template provides a complete boilerplate for building a LightningDataModule with all essential methods and best practices for data handling. """ import lightning as L from torch.utils.data import Dataset, DataLoader, random_split import torch class Cust...
329
9,354
scientific-agent-skills
skills/pytorch-lightning/scripts/quick_trainer_setup.py
.py
""" Quick Trainer Setup Examples for PyTorch Lightning. This script provides ready-to-use Trainer configurations for common use cases. Copy and modify these configurations for your specific needs. """ import lightning as L from lightning.pytorch.callbacks import ( ModelCheckpoint, EarlyStopping, LearningR...
474
13,843
scientific-agent-skills
skills/simpy/scripts/resource_monitor.py
.py
#!/usr/bin/env python3 """Bounded resource monitoring and deterministic event tracing for SimPy.""" from __future__ import annotations import argparse import csv import io import json from dataclasses import asdict, dataclass from functools import wraps from typing import TYPE_CHECKING, Any, Callable if TYPE_CHECKIN...
475
15,945
scientific-agent-skills
skills/simpy/scripts/event_trace_summary.py
.py
#!/usr/bin/env python3 """Summarize bounded event-trace JSONL or ResourceMonitor CSV artifacts.""" from __future__ import annotations import argparse import csv from collections import Counter from pathlib import Path from typing import Any from _common import ( MAX_TRACE_RECORDS, CliError, checked_input...
297
10,769
scientific-agent-skills
skills/simpy/scripts/_common.py
.py
#!/usr/bin/env python3 """Shared bounded-I/O and statistical helpers for the SimPy CLIs.""" from __future__ import annotations import hashlib import json import math import os import stat import tempfile from collections.abc import Iterable, Mapping from pathlib import Path from statistics import fmean, stdev from ty...
474
15,134
scientific-agent-skills
skills/simpy/scripts/bounded_queue_scenario.py
.py
#!/usr/bin/env python3 """Run a bounded finite-horizon queue scenario from allowlisted JSON.""" from __future__ import annotations import argparse import json from pathlib import Path from typing import Any from _common import ( MAX_TRACE_RECORDS, CliError, emit_json, emit_text, integer, load...
127
3,609
scientific-agent-skills
skills/simpy/scripts/replication_runner.py
.py
#!/usr/bin/env python3 """Run independent bounded replications and compute Student-t intervals.""" from __future__ import annotations import argparse from dataclasses import dataclass from typing import Any from _common import ( MAX_REPLICATIONS, CliError, emit_json, finite_number, integer, l...
195
6,234
scientific-agent-skills
skills/simpy/scripts/basic_simulation_template.py
.py
#!/usr/bin/env python3 """Bounded, reproducible SimPy queue template with independent random streams.""" from __future__ import annotations import argparse import random from dataclasses import asdict, dataclass, field from statistics import fmean from typing import TYPE_CHECKING, Any if TYPE_CHECKING: import si...
416
13,197
scientific-agent-skills
skills/simpy/scripts/validate_simulation_config.py
.py
#!/usr/bin/env python3 """Validate bounded queue or replication JSON without running a simulation.""" from __future__ import annotations import argparse from dataclasses import asdict from typing import Any from _common import CliError, emit_json, load_json_object from basic_simulation_template import QueueConfig fr...
112
3,679
scientific-agent-skills
skills/shap/scripts/tabular_report.py
.py
#!/usr/bin/env python3 """Generate a validated SHAP 0.52 tabular report from a built-in dataset. The script is intentionally self-contained: it downloads no data and loads no serialized model. Use it as a modern template for Explanation slicing, probability-space TreeExplainer output, additivity validation, and figure...
327
9,918
scientific-agent-skills
skills/qutip/scripts/qobj_model_validator.py
.py
#!/usr/bin/env python3 """Validate a bounded numeric QuTiP model described by strict JSON.""" from __future__ import annotations import argparse import math import re from collections.abc import Mapping from typing import Any from _common import ( MAX_MODEL_OBJECTS, QUTIP_VERSION, CliError, add_outpu...
328
10,932
scientific-agent-skills
skills/qutip/scripts/solver_config_planner.py
.py
#!/usr/bin/env python3 """Create a bounded QuTiP 5 solver and validation plan without simulation.""" from __future__ import annotations import argparse from typing import Any from _common import ( DEFAULT_SEED, MAX_TIME, MAX_TIME_POINTS, MAX_TRAJECTORIES, QUTIP_VERSION, CliError, add_outp...
298
10,090
scientific-agent-skills
skills/qutip/scripts/_common.py
.py
#!/usr/bin/env python3 """Shared bounded-I/O and validation helpers for the QuTiP CLIs.""" from __future__ import annotations import json import math import os import stat import sys import tempfile from collections.abc import Callable, Iterable, Mapping, Sequence from pathlib import Path from typing import Any QUT...
371
12,072
scientific-agent-skills
skills/qutip/scripts/result_audit.py
.py
#!/usr/bin/env python3 """Audit portable QuTiP skill JSON without loading Python objects.""" from __future__ import annotations import argparse import math from collections.abc import Mapping from typing import Any from _common import ( MAX_SWEEP_RUNS, MAX_TIME_POINTS, QUTIP_VERSION, CliError, ad...
396
12,043
scientific-agent-skills
skills/qutip/scripts/steady_state_spectrum_planner.py
.py
#!/usr/bin/env python3 """Plan bounded steady-state and spectrum calculations for QuTiP 5.""" from __future__ import annotations import argparse import math from typing import Any from _common import ( MAX_ABS_FREQUENCY, MAX_FREQUENCY_POINTS, MAX_HILBERT_DIMENSION, MAX_TIME, QUTIP_VERSION, Cl...
246
7,981
scientific-agent-skills
skills/qutip/scripts/two_level_simulation.py
.py
#!/usr/bin/env python3 """Run a bounded synthetic two-level open-system simulation.""" from __future__ import annotations import argparse import math from dataclasses import asdict, dataclass from typing import Any from _common import ( DEFAULT_SEED, MAX_ABS_FREQUENCY, MAX_RATE, MAX_TIME, MAX_TIM...
395
12,724
scientific-agent-skills
skills/qutip/scripts/convergence_sweep.py
.py
#!/usr/bin/env python3 """Run bounded deterministic or trajectory convergence sweeps.""" from __future__ import annotations import argparse from typing import Any from _common import ( DEFAULT_SEED, MAX_SWEEP_RUNS, MAX_TIME_POINTS, MAX_TOTAL_SWEEP_TRAJECTORIES, MAX_TRAJECTORIES, QUTIP_VERSION...
359
12,418
scientific-agent-skills
skills/bulk-rnaseq/scripts/build_counts_matrix.py
.py
#!/usr/bin/env python3 """Assemble a gene-level counts matrix from RNA-seq quantification output. Bridges the upstream (Salmon / STAR / featureCounts) and downstream (PyDESeq2) halves of a bulk RNA-seq pipeline. Writes: counts.csv genes x samples, INTEGER counts (never TPM/FPKM) metadata_template.csv ...
204
8,081
scientific-agent-skills
skills/bulk-rnaseq/scripts/validate_samplesheet.py
.py
#!/usr/bin/env python3 """Validate a bulk RNA-seq samplesheet (and optional design metadata). Catches the cheap-to-miss, expensive-to-debug problems before you spend compute: missing/duplicate FASTQs, inconsistent paired/single-end rows, invalid strandedness, and (with --metadata) too few replicates or batch fully con...
207
8,130
claude-plugins-official
plugins/claude-security/hooks/banner_notice.py
.py
#!/usr/bin/env python3 """Show the Claude Security banner as a display-only systemMessage. Always exits 0 with either the banner or no output. """ import contextlib import json import os import sys from typing import cast PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LAUNCH_NOTICE = "Laun...
100
3,753
claude-plugins-official
plugins/claude-security/scripts/write_scan_meta.py
.py
#!/usr/bin/env python3 """Write scan-meta.json for a run: the record of what was scanned. Captures the revision from git itself and, for a whole-repository scan, the tree's top-level directories, printed as a JSON array on a `top_level_dirs:` line and recorded in the meta file. Usage: write_scan_meta.py <run_dir> <...
232
8,212
claude-plugins-official
plugins/claude-security/scripts/patch_artifacts.py
.py
#!/usr/bin/env python3 """Render the suggested-fix products from a patch run directory. Reads the run's `patches.json` and raw `F<n>.diff` files, and writes into the report's `patches/` directory: * `F<n>.patch` -- the raw diff behind an explanatory comment header; * `F<n>.md` -- a short note per finding, whether...
878
34,454
claude-plugins-official
plugins/claude-security/scripts/render_report.py
.py
#!/usr/bin/env python3 """Render a scan's machine-readable artifacts from its run directory. Writes CLAUDE-SECURITY-RESULTS.jsonl (one finding per line, fields in a fixed order) and the CLAUDE-SECURITY-REVISION-<tag>.json stamp, places the report markdown beside them, then removes the scan's run directory now that its...
652
24,126
claude-plugins-official
plugins/security-guidance/hooks/_base.py
.py
""" Shared low-level helpers for the security-guidance hook modules. This module exists so that ``patterns``/``session_state``/``gitutil`` can use ``debug_log`` without importing ``security_reminder_hook`` (which would be a circular import). It must stay free of any other intra-plugin imports. """ import json import o...
232
10,176
claude-plugins-official
plugins/security-guidance/hooks/ensure_agent_sdk.py
.py
#!/usr/bin/env python3 """SessionStart bootstrap: ensure claude_agent_sdk is importable for the agentic commit reviewer. If claude_agent_sdk already imports in the current python3, this is a no-op. Otherwise it creates a venv at ~/.claude/security/agent-sdk-venv and installs the SDK there. security_reminder_hook.py pr...
863
41,917
claude-plugins-official
plugins/security-guidance/hooks/session_state.py
.py
""" Per-session state-file plumbing for the security-guidance plugin. Holds the JSON state file location, fcntl-locked read-modify-write helper, and old-file GC. Side-effect-free at import time (no env-var reads beyond ``CLAUDE_CODE_REMOTE_SESSION_ID`` inside the helpers). The ``atomic_check_*`` helpers that build on...
162
5,649
claude-plugins-official
plugins/security-guidance/hooks/security_reminder_hook.py
.py
#!/usr/bin/env python3 """ Security Guidance Plugin for Claude Code A hooks-based plugin that guides Claude toward writing more secure code. It runs as UserPromptSubmit, PostToolUse, and Stop hooks via the Claude Code plugin system. ## Architecture The plugin has two layers: 1. **Pattern-based rules (PostToolUse, e...
2,326
111,593
claude-plugins-official
plugins/security-guidance/hooks/diffstate.py
.py
""" Git-derived diff/review-state helpers for the security-guidance plugin. Extracted from security_reminder_hook.py for readability. Re-exported there so callers keep resolving bare names through the hook module's globals β€” tests that ``monkeypatch.setattr(hook, "<fn>", …)`` continue to work without retargeting. """ ...
472
20,986
claude-plugins-official
plugins/security-guidance/hooks/llm.py
.py
""" LLM-based security analysis for the security-guidance plugin. Owns the API config and every function that calls the Claude API (raw HTTP via ``_call_claude`` and the Agent-SDK ``agentic_review``). ``security_reminder_hook`` re-exports every name below so handlers β€” and tests that monkeypatch ``hook.X`` and then ca...
1,767
115,687
claude-plugins-official
plugins/security-guidance/hooks/gitutil.py
.py
""" Leaf git/subprocess helpers and diff parsing for the security-guidance plugin. Everything here is a thin wrapper over ``git``/``subprocess`` plus pure diff-text parsing and source-file classification. None of these functions reference any name that the test suite monkeypatches on ``security_reminder_hook`` and the...
794
34,900
claude-plugins-official
plugins/security-guidance/hooks/patterns.py
.py
""" Regex-based security pattern definitions for the security-guidance plugin. Pure data + one pure helper. No env-var reads, no I/O, no debug_log β€” kept side-effect-free so it can be imported in isolation. """ from enum import IntEnum _JS_EXTS = (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts", ".vue",...
361
18,474
claude-plugins-official
plugins/hookify/hooks/stop.py
.py
#!/usr/bin/env python3 """Stop hook executor for hookify plugin. This script is called by Claude Code when agent wants to stop. It reads .claude/hookify.*.local.md files and evaluates stop rules. """ import os import sys import json # Add plugin root to Python path for imports PLUGIN_ROOT = os.environ.get('CLAUDE_PL...
56
1,403
claude-plugins-official
plugins/hookify/hooks/userpromptsubmit.py
.py
#!/usr/bin/env python3 """UserPromptSubmit hook executor for hookify plugin. This script is called by Claude Code when user submits a prompt. It reads .claude/hookify.*.local.md files and evaluates rules. """ import os import sys import json # Add plugin root to Python path for imports PLUGIN_ROOT = os.environ.get('...
55
1,389
claude-plugins-official
plugins/hookify/hooks/pretooluse.py
.py
#!/usr/bin/env python3 """PreToolUse hook executor for hookify plugin. This script is called by Claude Code before any tool executes. It reads .claude/hookify.*.local.md files and evaluates rules. """ import os import sys import json # Add plugin root to Python path for imports PLUGIN_ROOT = os.environ.get('CLAUDE_P...
67
1,852
claude-plugins-official
plugins/hookify/hooks/posttooluse.py
.py
#!/usr/bin/env python3 """PostToolUse hook executor for hookify plugin. This script is called by Claude Code after a tool executes. It reads .claude/hookify.*.local.md files and evaluates rules. """ import os import sys import json # Add plugin root to Python path for imports PLUGIN_ROOT = os.environ.get('CLAUDE_PLU...
63
1,622
claude-plugins-official
plugins/hookify/core/rule_engine.py
.py
#!/usr/bin/env python3 """Rule evaluation engine for hookify plugin.""" import re import sys from functools import lru_cache from typing import List, Dict, Any, Optional # Import from local module from core.config_loader import Rule, Condition # Cache compiled regexes (max 128 patterns) @lru_cache(maxsize=128) def ...
314
10,711
tinygrad
sz.py
.py
#!/usr/bin/env python3 import os, sys import token import tokenize import itertools from tabulate import tabulate from tinygrad.uop import Ops from tinygrad.helpers import ContextVar TOKEN_WHITELIST = [token.OP, token.NAME, token.NUMBER, token.STRING] def is_docstring(t): return t.type == token.STRING and t.string....
96
4,545
tinygrad
conftest.py
.py
import os, pytest, signal, threading @pytest.hookimpl(wrapper=True) def pytest_runtest_call(item): t = threading.Timer(int(os.getenv("TEST_TIMEOUT", 300)), os.kill, args=(os.getpid(), signal.SIGABRT)) t.start() try: yield finally: t.cancel() t.join()
11
268
tinygrad
extra/gradcheck.py
.py
import numpy as np from tinygrad.tensor import Tensor, _to_np_dtype def mask_like(like, mask_inx, mask_value = 1.0): mask = np.zeros(like.shape, dtype=_to_np_dtype(like.dtype)).reshape(-1) mask[mask_inx] = mask_value return mask.reshape(like.shape) def jacobian(func, input): output = func(input) ji = input...
52
1,641
tinygrad
extra/bench_log.py
.py
import time, atexit, uuid from enum import Enum from tinygrad.device import Device from tinygrad.helpers import DEBUG, ContextVar, getenv, GlobalCounters BENCHMARK_LOG = ContextVar("BENCHMARK_LOG", "") if BENCHMARK_LOG: from influxdb_client_3 import InfluxDBClient3, Point, WriteOptions, write_client_options from...
112
3,649
tinygrad
extra/hip_large_kernel.py
.py
from tinygrad.device import Device, Buffer from tinygrad.dtype import dtypes, _to_np_dtype dev = Device.default mbin = dev.compiler.compile(""" typedef long unsigned int size_t; extern "C" __attribute__((device, const)) size_t __ockl_get_group_id(unsigned int); extern "C" __attribute__((global)) void __attribute__((am...
26
922
tinygrad
extra/hook_cuda.py
.py
import ctypes, struct, platform, pathlib, os, binascii from hexdump import hexdump from tinygrad.helpers import to_mv, DEBUG, getenv from tinygrad.runtime.autogen import libc, cuda from tinygrad.device import CPUProgram from tinygrad.runtime.support.elf import elf_loader from tinygrad.runtime.ops_cuda import cu_time_ex...
242
9,436
tinygrad
extra/thneed.py
.py
# this can be constructed from a cl_cache or loaded from a thneed file import time import struct import json import traceback import numpy as np from tinygrad.runtime.ops_cl import CLProgram, compile_gpu from tinygrad.device import Device from tinygrad.helpers import DEBUG, getenv from collections import defaultdict im...
288
11,615
tinygrad
extra/introspection.py
.py
import gc from tinygrad.helpers import prod from tinygrad.uop.ops import UOp from tinygrad.device import Buffer from tinygrad import Tensor, GlobalCounters def print_objects(): #gc.collect() tensors = [x for x in gc.get_objects() if isinstance(x, Tensor)] tensor_ram_used = sum([prod(x.shape)*4 for x in tensors])...
50
2,042
tinygrad
extra/onnx_helpers.py
.py
from tinygrad import Tensor from tinygrad.tensor import _to_np_dtype from tinygrad.nn.onnx import OnnxRunner, OnnxValue import numpy as np import onnxruntime as ort ort_options = ort.SessionOptions() ort_options.log_severity_level = 3 def get_example_inputs(graph_inputs:dict[str, OnnxValue], config={}): """ Genera...
168
7,112
tinygrad
extra/training.py
.py
import numpy as np from tinygrad.tensor import Tensor from tinygrad.helpers import trange, Context from tinygrad.engine.jit import TinyJit def train(model, X_train, Y_train, optim, steps, BS=128, lossfn=lambda out,y: out.sparse_categorical_crossentropy(y), transform=lambda x: x, target_transform=lambda x: x, ...
58
2,211
tinygrad
extra/f16_decompress.py
.py
from tinygrad import Tensor def bit_extract(x: Tensor, e: int, s: int) -> Tensor: mask = (1 << (e - s + 1)) - 1 return (x >> s) & mask def u16_to_f16(x: Tensor) -> Tensor: sign = bit_extract(x, 15, 15).bool() exponent = bit_extract(x, 14, 10).float() fraction = bit_extract(x, 9, 0).float() return sign.whe...
17
613
tinygrad
extra/archprobe.py
.py
# copying the kernels from https://github.com/microsoft/ArchProbe into Python import numpy as np import pickle from tinygrad.runtime.ops_cl import CLProgram, CLBuffer from tinygrad import dtypes from tqdm import trange, tqdm from matplotlib import pyplot as plt tests = {} def register_test(fxn): tests[fxn.__name__] ...
155
5,458
tinygrad
extra/lr_scheduler.py
.py
import math from typing import List from tinygrad.nn.optim import Optimizer from tinygrad.tensor import Tensor class LR_Scheduler: def __init__(self, optimizer: Optimizer): self.optimizer = optimizer self.epoch_counter = Tensor([0], device=self.optimizer.device) def get_lr(self): pass def schedule_step...
92
3,852
tinygrad
extra/gemm_fragment.py
.py
""" tilelang-style matmul_relu written with tinygrad UOp APIs. Reference tilelang kernel: @tilelang.jit def matmul_relu(A, B, block_M=64, block_N=64, block_K=64, dtype=T.float16, accum_dtype=T.float32): M, N, K = T.const('M, N, K') C = T.empty([M, N], dtype) with T.Kernel(T.ceildiv(N,...
140
6,726
tinygrad
extra/export_model.py
.py
from typing import Tuple, Dict, List, Optional from tinygrad.dtype import DType, dtypes, AddrSpace from tinygrad.tensor import Tensor from tinygrad.device import Device, Buffer from tinygrad.engine.jit import TinyJit from tinygrad.nn.state import get_state_dict from tinygrad.helpers import Context, to_mv, prod from tin...
304
17,036
tinygrad
extra/benchmark_llm.py
.py
import argparse, time from tinygrad.llm.model import Transformer if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--model", required=True, help="path to gguf model") parser.add_argument("--max-context", type=int, default=8192, help="max context length (default: %(default)s)") ...
32
1,480
tinygrad
extra/multitensor.py
.py
import numpy as np from tinygrad import Tensor, Device, GlobalCounters from tinygrad.helpers import Timing d0, d1 = f"{Device.DEFAULT}:1", f"{Device.DEFAULT}:2" N = 256 FLOPS = N*N*N*2 # LazyBuffer should make three fields lists: self.st (all must have the same shape), self.realized, and self.device def explicit_sha...
60
1,968
tinygrad
extra/weekly_commits_table.py
.py
# extra/weekly_commits_table.py import os, subprocess, datetime as dt NAMES = ["chenyu","George Hotz","nimlgen","qazal","wozeparrot","Christopher Milan"] REPO = os.environ.get("REPO_PATH",".") today = dt.date.today() days = [(today - dt.timedelta(i)).strftime("%Y-%m-%d") for i in range(6,-1,-1)] seen = {d:{n:False ...
44
1,504
tinygrad
extra/huggingface_onnx/run_models.py
.py
import onnx, yaml, tempfile, time, argparse, json from pathlib import Path from typing import Any from tinygrad.nn.onnx import OnnxRunner from extra.onnx_helpers import validate, get_example_inputs from extra.huggingface_onnx.huggingface_manager import DOWNLOADS_DIR, snapshot_download_with_retry def get_config(root_pa...
109
5,344
tinygrad
extra/huggingface_onnx/huggingface_manager.py
.py
import yaml import time import requests import argparse from pathlib import Path from huggingface_hub import list_models, HfApi, snapshot_download from tinygrad.helpers import _ensure_downloads_dir DOWNLOADS_DIR = _ensure_downloads_dir() / "models" from tinygrad.helpers import tqdm def snapshot_download_with_retry(*, ...
230
8,288
tinygrad
extra/nv_pma/collect.py
.py
import pickle, os, sys, functools, numpy as np from pathlib import Path os.environ["DEV"] = "CUDA" os.environ["PROFILE"] = os.environ.get("PROFILE", "2") from extra.nv_pma.cupti import cu_prof_ext cu_prof_ext.enable_auto() from tinygrad import Tensor, Device if not os.environ.get("IOCTL") or not os.environ.get("GRAB...
136
4,090
tinygrad
extra/nv_pma/decode.py
.py
#!/usr/bin/env python3 from __future__ import annotations import enum, collections from typing import Iterator from tinygrad.helpers import colored from tinygrad.renderer.amd.sqtt import PacketType, bits # ═══════════════════════════════════════════════════════════════════════════════ # STALL REASONS # ═══════════════...
190
10,088
tinygrad
extra/nv_pma/test/test_nvprof.py
.py
import pickle, unittest from collections import Counter from pathlib import Path from extra.nv_pma.decode import decode from tinygrad.helpers import DEBUG EXAMPLES_DIR = Path(__file__).parent.parent / "examples" EXAMPLES_5090_DIR = Path(__file__).parent.parent / "examples_5090" def decode_and_aggregate(raw_dumps: li...
77
3,951
tinygrad
extra/nv_pma/cupti/cu_prof_ext.py
.py
from __future__ import annotations import ctypes from tinygrad.helpers import DEBUG, getenv from extra.nv_pma.cupti import cupti def stall_reason_name(reason: int) -> str: name = cupti.CUpti_ActivityPCSamplingStallReason.get(reason) return name.replace("CUPTI_ACTIVITY_PC_SAMPLING_STALL_", "").lower() if name else ...
165
7,384
tinygrad
extra/nv_pma/cupti/__init__.py
.py
# CUPTI autogen loader for nv_pma # To regenerate: REGEN=1 python -c "import extra.nv_pma.cupti" import importlib, pathlib from tinygrad.helpers import getenv root = pathlib.Path(__file__).parents[3] here = pathlib.Path(__file__).parent def load(name, dll, files, **kwargs): if not (f:=here/f"{name}.py").exists() or...
27
1,465
tinygrad
extra/qcom_gpu_driver/opencl_ioctl.py
.py
# type: ignore import ctypes, ctypes.util, struct, fcntl, re from hexdump import hexdump from copy import deepcopy import pathlib, sys from tinygrad.helpers import to_mv, getenv from tinygrad.runtime.autogen import mesa sys.path.append(pathlib.Path(__file__).parent.parent.parent.as_posix()) IOCTL = getenv("IOCTL", 0) ...
218
9,642
tinygrad
extra/qcom_gpu_driver/qcom_opencl_interop.py
.py
import ctypes, array from hexdump import hexdump from tinygrad.runtime.ops_cl import CLDevice from tinygrad.helpers import getenv, to_mv, mv_address from tinygrad.dtype import dtypes from tinygrad import Tensor, TinyJit from tinygrad.runtime.autogen import opencl as cl if getenv("IOCTL"): import extra.qcom_gpu_driver.o...
98
3,618
tinygrad
extra/qcom_gpu_driver/msm_kgsl.py
.py
# type: ignore # -*- coding: utf-8 -*- # # TARGET arch is: [] # WORD_SIZE is: 8 # POINTER_SIZE is: 8 # LONGDOUBLE_SIZE is: 16 # import ctypes class AsDictMixin: import sys if sys.version_info >= (3, 14): _layout_ = 'ms' @classmethod def as_dict(cls, self): result = {} if not isinstance...
1,038
30,558
tinygrad
extra/dsp/invoke_bug_2.py
.py
from tinygrad.runtime.ops_dsp import DSPDevice kernel = """__attribute__((noinline)) void r_64_4_4_64_4_4_4(float* restrict __attribute__((align_value(128))) data0, const float* restrict __attribute__((align_value(128))) data1, const float* restrict __attribute__((align_value(128))) data2, const float* restrict __attr...
280
10,795
tinygrad
extra/dsp/compile.py
.py
#!/usr/bin/env python3 import os, ctypes, time, fcntl, mmap import llvmlite.binding as llvm from tinygrad.helpers import getenv, to_mv from tinygrad.runtime.support.elf import elf_loader from hexdump import hexdump from tinygrad.runtime.autogen import libc if getenv("IOCTL"): import run # noqa: F401 # pylint: disable=u...
126
4,528
tinygrad
extra/dsp/invoke_bug.py
.py
from tinygrad.runtime.ops_dsp import DSPDevice kernel = """__attribute__((noinline)) void r_6_10_13_4_4_29(float* restrict __attribute__((align_value(128))) data0, const float* restrict __attribute__((align_value(128))) data1, const float* restrict __attribute__((align_value(128))) data2, const float* restrict __attri...
327
20,810
tinygrad
extra/dsp/run.py
.py
# mypy: ignore-errors #!/usr/bin/env python3 import os, ctypes, ctypes.util, struct, platform, time from tinygrad.runtime.autogen import libc, qcom_dsp def to_mv(ptr, sz) -> memoryview: return memoryview(ctypes.cast(ptr, ctypes.POINTER(ctypes.c_uint8 * sz)).contents).cast("B") from hexdump import hexdump def get_struc...
153
6,131
tinygrad
extra/dsp/hook.py
.py
import os print("from import") del os.environ["LD_PRELOAD"] import ctypes, ctypes.util from extra.dsp.run import install_hook, ioctl, libc, get_struct, qcom_dsp, format_struct, to_mv, hexdump @ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_long) d...
102
4,398
tinygrad
extra/dsp/opt.py
.py
from tinygrad import Device # PATH=/opt/homebrew/opt/llvm/bin:$PATH python3 extra/dsp/opt.py if __name__ == "__main__": compiler = Device["DSP"].compiler lib = compiler.compile(""" typedef long HVX_Vector __attribute__((__vector_size__(128))) __attribute__ ((aligned(128))); typedef long HVX_VectorPair __attribut...
28
988
tinygrad
extra/dsp/run_3.py
.py
#!/usr/bin/env python3 import os, ctypes, ctypes.util, struct, platform, pathlib, contextlib, mmap, array from threading import Thread from tinygrad.runtime.autogen import qcom_dsp from tinygrad.helpers import round_up, mv_address, to_mv from hexdump import hexdump def get_struct(argp, stype): return ctypes.cast(cty...
313
12,315
tinygrad
extra/dsp/snpe_logs/parse.py
.py
di = open("dlc_info_2").read().split("\n") layers = {} for l in di: if not l.startswith("| "): continue if l.startswith("| |"): continue ll = [x.strip() for x in l.split("|")] if ll[1] == "Id": continue layers[int(ll[1])] = (ll[2], ll[6]) hp = open("high_perf_2").read().split("Layer Times:")[1].strip().sp...
22
569
tinygrad
extra/llama_kernels/__init__.py
.py
from __future__ import annotations import functools, pathlib from dataclasses import replace from tinygrad import Tensor, dtypes from tinygrad.uop.ops import shape_to_shape_arg from tinygrad.runtime.support.compiler_amd import HIPCCCompiler FP8_MAX = 448.0 NUM_WG, THREADS_PER_WG = 1024, 256 # per-device abs max witho...
48
2,012
tinygrad
extra/llama_kernels/quantize_mxfp4/__init__.py
.py
import functools, math, pathlib from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo from tinygrad.renderer import Estimates from extra.llama_kernels import alloc_like, compile_hip @functools.cache def _custom_quantize_mxfp4(row_fp4:UOp, row_scale:UOp, col_fp4:UOp, col_scale:UOp, x:UOp...
37
2,640
tinygrad
extra/llama_kernels/fused_ce/__init__.py
.py
import functools from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType @functools.cache def _custom_fused_ce_loss_fwd(loss_out:UOp, max_out:UOp, lse_out:UOp, logits:UOp, targets:UOp, vocab:int, rows:int, seq:int, label_smoothing:float) -> UOp: r...
99
5,253
tinygrad
extra/llama_kernels/fused_rmsnorm_mul_quantize_fp8/__init__.py
.py
from __future__ import annotations import functools, pathlib from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo from tinygrad.renderer import Estimates from extra.llama_kernels import NUM_WG, THREADS_PER_WG, alloc_like, alloc_local, dname_of, compile_hip def _src() -> str: return (pa...
151
9,304
tinygrad
extra/llama_kernels/quantize_mxfp8_fused/__init__.py
.py
import functools from tinygrad import Tensor, dtypes from tinygrad.helpers import prod from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType from extra.llama_kernels import FP8_MAX, THREADS_PER_WG, alloc_like BLK = 32 PACK = 4 @functools.cache def _custom_quantize_mxfp8(fp8_out:UOp, e8_out:UOp, si_out:UOp, x:UO...
72
3,135
tinygrad
extra/llama_kernels/fused_silu_mul_quantize_mxfp8/__init__.py
.py
import functools from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType from extra.llama_kernels import FP8_MAX, THREADS_PER_WG, alloc_like BLK = 32 PACK = 4 LOG2E = 1.4426950408889634 @functools.cache def _custom_silu_mul_quantize_mxfp8(fp8_out:UOp, e8_out:UOp, si_out:UOp, x_...
105
4,879
tinygrad
extra/llama_kernels/quantize_fp8_delayed/__init__.py
.py
import functools from tinygrad import Tensor, dtypes from tinygrad.dtype import AddrSpace from tinygrad.helpers import prod from tinygrad.uop.ops import UOp, Ops, KernelInfo, AxisType from extra.llama_kernels import FP8_MAX, NUM_WG, THREADS_PER_WG, alloc_like @functools.cache def _custom_quantize_fp8_with_amax(fp8_out...
97
4,646
tinygrad
extra/llama_kernels/rmsnorm/__init__.py
.py
from __future__ import annotations import functools from tinygrad import Tensor from tinygrad.uop.ops import UOp def rmsnorm_fwd(x_in:Tensor, eps:float) -> tuple[Tensor, Tensor]: x = x_in.float() rrms = (x.square().mean(-1, keepdim=True) + eps).rsqrt() return (x * rrms).cast(x_in.dtype), rrms @functools.cache d...
25
968
tinygrad
extra/llama_kernels/cast_amax/__init__.py
.py
from __future__ import annotations import functools, pathlib from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo from tinygrad.renderer import Estimates from extra.llama_kernels import NUM_WG, THREADS_PER_WG, compile_cpp, alloc_like, dname_of # module-level mailbox: grad_xw13 UOp -> (...
74
4,666
tinygrad
extra/llama_kernels/swiglu/__init__.py
.py
import functools, math from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, KernelInfo from tinygrad.renderer import Estimates from extra.llama_kernels import alloc_like LOG2E = 1.4426950408889634 @functools.cache def _custom_swiglu(out:UOp, x_w13:UOp) -> UOp: rows, hidden = math.prod(x_w13.shape[:...
50
2,542
tinygrad
extra/llama_kernels/transpose_quantize_mxfp8/__init__.py
.py
from __future__ import annotations import functools, pathlib from tinygrad import Tensor, dtypes from tinygrad.uop.ops import UOp, Ops, KernelInfo from tinygrad.renderer import Estimates from extra.llama_kernels import THREADS_PER_WG, alloc_like, dname_of, compile_hip TILE_N = THREADS_PER_WG # 256 BLK = 32 @functoo...
38
2,004
tinygrad
extra/thunder/tiny/fa.py
.py
import math from tinygrad import Tensor, dtypes from tinygrad.helpers import DEBUG from tinygrad.uop.ops import UOp, Ops from extra.thunder.tiny.tk import WARP_THREADS from extra.thunder.tiny.tk.kernel import Kernel from extra.thunder.tiny.tk.tiles import GL, TileLayout NUM_WORKERS = 1 Q_BLOCK_SIZE = 32 KV_BLOCK_SIZ...
417
20,288
tinygrad
extra/thunder/tiny/visualize_tile.py
.py
from tinygrad.helpers import colored WARP_THREADS = 64 BASE_TILE_ROWS = 16 BASE_TILE_COLS = 16 BASE_TILE_NEPT = (BASE_TILE_ROWS * BASE_TILE_COLS) // WARP_THREADS DTYPE_SIZE = 2 INST = "ds_read_b64" def row_col(threadIdx_x): local_warpid = threadIdx_x // WARP_THREADS warp_laneid = threadIdx_x % WARP_THREADS ret...
157
4,739
tinygrad
extra/thunder/tiny/tk/kernel.py
.py
from contextlib import AbstractContextManager from tinygrad.uop.ops import UOp, KernelInfo, AxisType, AddrSpace from extra.thunder.tiny.tk import WARP_THREADS from extra.thunder.tiny.tk.group import Group from extra.thunder.tiny.tk.tiles import GL, ST_16X16, ST, RT_16X16, RT, RV, TileLayout, VecLayout class _tk_range:...
114
4,166
tinygrad
extra/thunder/tiny/tk/__init__.py
.py
from tinygrad.device import Device if Device.DEFAULT == "AMD": WARP_THREADS = 64 else: WARP_THREADS = 32
7
110
tinygrad
extra/thunder/tiny/tk/group.py
.py
import math from typing import cast, Callable from tinygrad.uop.ops import AxisType, UOp from tinygrad.dtype import AddrSpace from tinygrad.helpers import prod from extra.thunder.tiny.tk import WARP_THREADS from extra.thunder.tiny.tk.tiles import ALL_TILES, ST, RT, RV, TileLayout, VecLayout class Group: def __init_...
487
21,823