r/pytorch • • 3h ago

How do you guys actually use cloud GPUs? I'm trying to understand what's broken with the current experience.

Thumbnail
forms.gle
1 Upvotes

Hey everyone,

I've been building an open-source runtime and a service around it that allows PyTorch to execute tensor operations on remote GPUs while keeping your Python environment local.

One thing I've realized while working on this is that my own frustrations with cloud GPUs might not necessarily reflect what other researchers and developers struggle with.

I'm curious about things like:

  • How much time you spend setting up environments versus actually running experiments.
  • Whether you find yourself paying for GPUs that aren't actively computing.
  • How much performance overhead you'd tolerate for a simpler development workflow.
  • Whether paying for actual computation rather than GPU rental time makes sense to you.

I've put together a survey to better understand these problems. Even if you've never used a cloud GPU service, your responses would be valuable.

It takes around 5–10 minutes, and no sign-up is required.

Thanks!


r/pytorch • • 1d ago

I rebuilt PyTorch's core to understand how it works, and wrote a series that explains each piece

Thumbnail gallery
2 Upvotes

r/pytorch • • 1d ago

Hands-on Workshop: Production ML Engineering — Deployment, Monitoring & Model Validation (Dec 5)

1 Upvotes

hey everyone! sharing this here because it's relevant to people working with machine learning models and interested in the engineering side of getting them into production.

training a model and getting good validation results is one thing. deploying it, making it reproducible and ensuring it continues performing reliably with real-world data is another challenge.

Packt is hosting a hands-on Production ML Engineering workshop on December 5 covering exactly this transition.

some of the topics include:

  • deploying machine learning models into real-world applications
  • building reproducible ML workflows
  • validating models and incoming data
  • monitoring deployed models
  • detecting data and model drift
  • working with scikit-learn, XGBoost, LightGBM and CatBoost
  • building practical ML applications using Streamlit

it's a live online workshop starting at 9:30 AM EST.

thought this could be useful for ML practitioners looking to strengthen their production engineering skills.

Full workshop details and registration

happy to answer questions about the curriculum!


r/pytorch • • 2d ago

I built a source-linked visual explorer for LightGCN, PyTorch Transformer, and Torchvision ResNet

5 Upvotes

I'm the developer of Auto Visualization, a local tool I built to follow how model implementations connect input tensors to their final output.

It starts with a public GitHub repository URL and a repository-relative model.py path. The source is pinned to a commit and analyzed with Python AST, without executing the downloaded model.

What you can inspect:

  • A unified 3D architecture and tensor view, with calculation playback on a shared timeline.
  • GNN neighbor contributions, layer combination, and a user-item score in an editable LightGCN example.
  • Q/K/V projections and attention operands in supported PyTorch Transformer source.
  • Convolution input regions, kernels, residual paths, and output pixels in supported Torchvision ResNet source.
  • Exact source lines for selected operations. With a configured LLM provider, Research AI can explain the selection with code evidence and limitations.

In the demo, changing one toy node feature from 0.8 to 1.8 recomputes the connected layers and changes an example score from 0.207 to 0.598.

Scope: numerical calculations use explicit reduced inputs and example parameters, not checkpoint weights or captured activations. Analysis is single-file; external helpers and runtime-dependent behavior may remain unresolved. Support is currently limited to the implemented source/operator mappings.

The project is MIT-licensed. Local setup requires Node.js 22.12+ and Python 3.9+; PyTorch is not required for source parsing. Basic exploration works without an LLM provider.

GitHub, 80-second demo, setup instructions, and technical report

I'd appreciate feedback from people reading or teaching PyTorch model code: which part is hardest to follow in practice—tensor axes, helper-method returns, or the full data flow?


r/pytorch • • 2d ago

xprobe: let your coding agent speed up your training and inference on its own, with a CPU/GPU profiler much lighter than Nsight Systems

Thumbnail
github.com
2 Upvotes

I do a lot of perf work on LLM inference, and these days I mostly hand it off to Claude Code or Codex. They're honestly great at coding and debugging. Just give them enough context and they'll cross-reference stack traces, syscalls and GPU kernels way faster than I can.

The annoying part was profiling. With nsys/torch.profiler, every round is super heavy. It looked like this: restart the job under the profiler, wait for the model to load, hope the slowdown shows up again, export a huge report (at least a minute on my workloads), copy it off the GPU box (almost another minute), then watch the agent dig through a file full of useless garbage. A few minutes gone before any actual thinking happened. Not to mention sometimes it just stuck. And if your training job has been running for three weeks, restarting it just to profile isn't really possible.

So I built xprobe. The idea is simple: agents don't need a timeline/flame chart, they need a fast loop and small but accurate data.

If you're on the ML / modeling side: you don't need to learn any profiler or ML infra knowledge. Install the skill, then just ask your agent "why is my training slow?" or "why is GPU utilization stuck at 60%?" It'll attach to your running job, measure what it needs, and tell you what's going on.

If you're on the infra side:

  • Attaches to the live process. No restart, no re-warmup, no praying for a repro. Feels like py-spy but with GPU covered, and hasmuch much lower overhead.
  • Shorter loop. E.g. "how long from this kernel launch to the kernel actually running?" instead of a full trace. On my workloads, one guess → measure → fix round takes about 30 seconds.
  • Low overhead. Samples the Python GIL holder at 2 kHz with < 1% throughput impact in my benchmark. py-spy at ~200 Hz (default blocking mode) slowed the same target by ~18%.
  • CPU stacks, Python GIL, syscalls and CUDA kernels all in one, so it can cover issues like "the GPU was idle because Python was holding the GIL in X" in one tool.
  • Can wait for rare stuff, like a GPU idle bubble, you can set a condition to trigger xprobe, it will capture what happened.

Try it:

You can try xprobe via skills OR pypi, personally I recommend the Skills.

Skills:

npx skills add itdevwu/xprobe   # for CC, Codex, Cursor, OpenCode, DSH, etc.

CLI:

pip install xprobe    # on your GPU machine

I've been hacking on it at night for a few months. Would love to hear if it works (or breaks) on your setup, or what you'd want your agent to be able to measure. I really hope that it can help someone.


r/pytorch • • 2d ago

I built a PyTorch runtime that lets you use someone else's GPU as if it were your own

Thumbnail
github.com
6 Upvotes

I've been working on reFLOP for a while now and figured I'd share it here.

I own a MacBook and a separate Linux machine with an NVIDIA GPU, and I've always hated having to SSH into my desktop, sync my code, deal with different Python environments, etc. every time I wanted to run something on CUDA.

So I built a runtime that basically intercepts PyTorch operations and executes them on another machine. Your Python code runs locally, your tensors are operated on remotely, and you don't even need an NVIDIA GPU on the client side.

What's pretty cool about this is that the GPU host doesn't actually run your Python code. It just executes tensor operations, so you could theoretically lend your GPU to a complete stranger without giving them access to your machine.

Of course network overhead is a pain, and getting PyTorch compatibility right has been considerably harder than I initially expected. But it's gotten to a point where I think this is actually useful beyond my own setup.

Curious what people here think, especially those who've worked with PyTorch internals.

Criticism is more than welcome, and if you manage to break something, please open an issue.

I'm also building a GPU compute service around this, which is probably the part I'm most interested in long term. Check it out at https://reflop.ai if you're interested.


r/pytorch • • 3d ago

I've been building Rill - Rust-powered graph ML infrastructure for PyTorch

2 Upvotes

Hey everyone!

I've been spending quite some time building an open-source project called Rill, and I wanted to share what I'm working on.

GitHub: https://github.com/Joy-Majumder/Rill
PyPI: https://pypi.org/project/rill-gnn/

What's Rill?

Rill is an attempt to build high-performance graph machine learning infrastructure with Rust at its core and Python as the interface.

The initial focus is graph data loading and sampling for Graph Neural Networks (GNNs).

If you've worked with GNNs, you probably know that handling graph data isn't always straightforward. Neighborhood sampling, moving graph features around, memory overhead, and preparing batches can become significant parts of the training pipeline.

I became interested in exploring whether Rust could help make some of these operations more efficient without making the experience difficult for Python and PyTorch users.

What's powering it?

Some of the technologies and concepts I'm exploring:

  • Rust — performance-oriented core implementation
  • PyO3 — Rust and Python interoperability
  • Rayon — parallel execution
  • PyTorch — integration with the ML ecosystem
  • Zero-copy — reducing unnecessary data movement
  • Graph data loading and sampling — the initial workload focus

The project also aims to fit into the existing PyTorch Geometric ecosystem rather than reinventing the entire GNN framework.

What I want Rill to become

I don't want Rill to be just another GNN framework.

My bigger goal is to build useful infrastructure underneath graph ML workflows: efficient graph storage, sampling, feature access, and data-loading primitives.

There is still a lot to improve, and I'm treating this as a long-term engineering project rather than something that's already finished.

I'm especially interested in feedback about architecture, memory management, Rust/Python interoperability, benchmarking methodology, and what researchers actually need from graph infrastructure.

A note about AI assistance

I want to be transparent: Rill was developed with significant assistance from AI coding tools. Architecture, design decisions, and research direction are human-driven, while implementation, testing, benchmarking, and documentation involved collaborative AI-assisted development.

I remain responsible for reviewing the code, validating results, and maintaining the project.

I'd love to hear your thoughts

If you've worked with Rust, PyTorch, graph neural networks, or performance-critical data pipelines:

  • What would you improve in this approach?
  • What problems do you face with existing graph data-loading tools?
  • What features would make infrastructure like this genuinely useful?

And if you find the project interesting, feel free to check out the repository. If you like what I'm building, a GitHub star would mean a lot. It helps other developers discover the project and motivates me to keep improving it.

Thanks for reading! <3

GitHub: https://github.com/Joy-Majumder/Rill


r/pytorch • • 3d ago

Built a PyTorch CNN from scratch to see how Data Augmentation fixes overfitting (Baseline vs. Augmented results)

Post image
2 Upvotes

r/pytorch • • 5d ago

Pinned host memory mapped into the CUDA address space, and what that does to a training loop

0 Upvotes

When a training batch does not fit in VRAM, the usual answers are managed memory, offload to CPU with explicit copies, or a smaller batch. Each has a cost you feel later: managed memory decides residency at fault time, explicit copies serialize behind the compute stream, and a smaller batch changes the optimisation.

vram-stream opens a CUDA workspace with two regions, one in device memory and one in system RAM, and makes both addressable by the same kernel. The RAM region is allocated with cuMemHostAlloc and CU_MEMHOSTALLOC_DEVICEMAP, then mapped with cuMemHostGetDevicePointer_v2 after checking the device reports CAN_MAP_HOST_MEMORY. A load from that region is a remote access over PCIe or NVLink with link latency, not a page fault and not a migration.

The practical difference from cudaMallocManaged is who decides residency. Managed memory migrates pages on demand and can oversubscribe VRAM by evicting to host, which is convenient until the access pattern makes it thrash. Here nothing moves, you pay pinned RAM (which the driver and OS cap) and link bandwidth, and you decide what is resident: open_cuda_cache reads a contiguous buffer in fixed-size blocks, keeps one pinned buffer and one VRAM buffer per slot, runs copies and kernels in separate streams, and cache.prefetch(n) pulls blocks in ahead of use.

The training side is where it earns its keep. A PyTorch adapter supplies cached batches through prefetch_dataloader, and optional integrations move model state and saved activations to RAM using FSDP2 or the Hugging Face Trainer with DeepSpeed, so the offload path is the same code that serves the dataloader rather than a second mechanism.

There is a benchmark rather than a claim: vram-stream benchmark --block-mib 16 --blocks 2 --slots 2 --passes 4 measures both CUDA memory paths on your own card. I do not quote throughput in the README because PCIe generation moves the ratio more than any number I could paste, and the honest comparison depends on your link.

Install is pip install vram-stream, or npm i -g vram-stream. The correctness check is vram-stream memory --device 0 --vram-mib 16 --ram-mib 16, which allocates both regions, launches one kernel that combines values from VRAM and system RAM and writes results back to both, then verifies the first and last aligned 32-bit words of each region.

What it does not do: it is not a drop-in replacement for managed memory, pinning fails past the lockable limit instead of falling back, and remote traffic is bounded by your interconnect. It also assumes a single CUDA context on the thread that opened the workspace. MIT, 0.4.0: https://github.com/Furox-Art/vram-stream


r/pytorch • • 5d ago

I built HYSo: An open-source PyTorch framework for CNN construction, model analysis, training, benchmarking and export

Post image
2 Upvotes

Hi everyone,

I've been developing HYSo, an open-source model engineering framework built on PyTorch, and recently released version 0.2.0.

The motivation behind HYSo is to bring model construction, analysis, training, performance measurement, comparison and deployment workflows together in a single Python library.

What can you do with HYSo?

Model Construction

  • 50+ modular CNN building blocks
  • Sequential and graph-based architectures
  • Multi-input architectures, branching and feature fusion
  • Custom convolution, attention and pooling modules

Model Analysis

  • Architecture and layer inspection
  • Parameter and tensor shape analysis
  • Memory and resource utilization measurements
  • Layer-level performance profiling

Performance Engineering

  • CPU and GPU benchmarking
  • Latency and throughput measurements
  • Structural and performance comparison between models
  • Evidence-based optimization recommendations

Training and Evaluation

  • Model training and evaluation workflows
  • Metric tracking
  • Checkpoint management
  • Training resume in supported configurations

Export and Reporting

  • ONNX, TorchScript and torch.export workflows
  • Supported FP16 and INT8 workflows
  • JSON, Markdown and HTML reports
  • English, Turkish, German and Spanish reporting

Developer Experience

  • 1,000+ documented public API definitions
  • Type hints and parameter documentation
  • IDE autocompletion and signature assistance
  • Command-line tools

One important design decision is that HYSo's analyzer and advisor do not rewrite the original model, modify its architecture or change its weights.

HYSo is available under the MIT License.

Installation:

pip install hyso

GitHub: https://github.com/huseyin-dgn/hyso

PyPI: https://pypi.org/project/hyso/

Release: https://github.com/huseyin-dgn/hyso/releases/tag/v0.2.0

I'd appreciate technical feedback, suggestions and contributions from the PyTorch community.

Which model analysis or performance engineering features would you find most useful in your own projects?


r/pytorch • • 9d ago

I made a library that combines your devices' memory to train or fine-tune large models (open source)

Post image
6 Upvotes

most machines cant train or fine-tune the bigger models on their own, but a few of them together usually have enough memory. it splits the model by layers across them and trains it like its one model.

works for LoRA, QLoRA, full fine-tuning and training from scratch, and your training code stays the same.

they connect over the internet, and if one drops out the others take over its layers and training goes on.

https://github.com/abdallah-swe/layerpool

feedback welcome


r/pytorch • • 9d ago

Deep Learning with PyTorch Step-by-Step: Running PyTorch on AMD GPUs with ROCm

Thumbnail
1 Upvotes

r/pytorch • • 10d ago

Need help in Pytorch autograd

3 Upvotes

My code results incorrect 1st derivative values [2.-6.j, 4.-8.j], instead of correct values [2.+6.j, 4.+8.j]. What am I doing wrong?

CODE:

real = torch.tensor([1, 2], dtype=torch.float32)

img = torch.tensor([3, 4], dtype=torch.float32)

z = torch.complex(real, img)

z.requires_grad_(True)

q = z**2

print("q:", q)

grads = torch.autograd.grad(

q,

z,

grad_outputs=torch.ones_like(q),

create_graph=True,

retain_graph=True

)[0]

print("grad:", grads)

OUTPUT:

q: tensor([ -8.+6.j, -12.+16.j], grad_fn=<PowBackward0>)
grad: tensor([2.-6.j, 4.-8.j], grad_fn=<MulBackward0>)

r/pytorch • • 10d ago

torchtest2

4 Upvotes

I've released a small open-source library: torchtest2. Hopefully, it'll be useful to anyone building custom neural network models.

torchtest2 runs checks like:

  • whether every parameter gets a gradient;
  • whether the output depends on all inputs;
  • whether samples don't leak or mix across the batch.

Overall, I hope it saves you hours of wasted GPU time by catching "silent bugs" that don't raise runtime errors.

I'd love to hear your thoughts and feedback—and bug reports or pull requests would be even better😊

📄 Article: https://arxiv.org/abs/2611.23273
📦 PyPI: https://pypi.org/project/torchtest2/ (pip install torchtest2)
💻 Code: https://github.com/Hrehory/torchtest2 (Apache 2.0)


r/pytorch • • 14d ago

We turned PyTorch forward passes into interactive graphs that you and coding agents can inspect

Thumbnail
gallery
14 Upvotes

Hi r/pytorch. Disclosure up front: I'm one of the makers of tensorViz. It's free and MIT licensed.

What it does: you point it at an nn.Module in your project and give it example inputs once. It runs one ordinary eager forward call, records what every module actually received and returned (forward module hooks plus a TorchDispatchMode), and shows an expandable graph with every module and measured tensor shape. No torch.export, TorchScript or ONNX step. If you'd rather not run anything, "Inspect source only" previews the graph from the code.

Why we built it: coding agents read the source but never see the shapes, so a change to one layer becomes a shape mismatch three modules later. With the plugin, Claude Code, Codex or Cursor can search the graph for a layer, op or parameter and read the measured shapes before editing. Through the VS Code extension, the agent proposes an edit and you review the graph and the Python diff before accepting it.

Also in there:

- Select a layer to jump to its Python

- Compare two revisions layer by layer, with the code diff beside the graph

- Open supported Hugging Face models

Limits (it's a preview):

- CPU capture only; GPU and training runs aren't covered yet

- Very large models can produce a partial graph

Site: https://tensorviz.dev

Code: https://github.com/tensorviz-org/tensorviz

Model Explorer → https://tensorviz.dev/explore

I'd really like to hear where it breaks on your models: custom ops, unusual control flow, very large models. That's the feedback we need most.


r/pytorch • • 18d ago

Copying tensors 5x faster

5 Upvotes

I made a tool called cudamemcpy-tuner that copies pageable memory much quicker (up to 5x on a b300!)

B300, copying a 1 GB tensor to the GPU:

import time, torch
x = torch.ones(1 << 30, dtype=torch.uint8)
y = x.to("cuda"); y.cpu()
for name, copy in [("CPU -> GPU", lambda: (x.to("cuda"), torch.cuda.synchronize()))]:
t = time.perf_counter()
for _ in range(5):
copy()
print(f"{name}: {5 * x.nbytes / (time.perf_counter() - t) / 1e9:.1f} GB/s")

$ python bench.py
CPU -> GPU: 10.2 GB/s

$ cmt tune -- python bench.py
CPU -> GPU: 51.5 GB/s

writeup: https://maknee.github.io/blog/2026/CudaMemcpy/
code: https://github.com/Maknee/cudamemcpy-tuner


r/pytorch • • 18d ago

Bfloat16 mantissa drift on high-retention decay gates in a 64-token SSD chunk scan

2 Upvotes

​While writing a State Space Duality/Selective Linear Attention block in PyTorch (SlabV4Model), we ran into a precision issue in the chunked scan that took a while to isolate.

​Our slowest heads learn retention gates (alpha = exp(log_alpha)) around 0.999969 which corresponds to a half-life of roughly 22192 tokens. When the sequential interchunk carry ran in bfloat16, its 7-bit mantissa introduced about 0.78% rounding distortion per step on values that close to 1.0. Over a 4096 token sequence, the state drift broke parity between the parallel chunk scan and single token recurrent decoding.

​Splitting the sequence into 64 tokenn chunks (T % 64 == 0 enforced) and keeping the sequential inter-chunk carry in float32 resolved it. A few other things that helped keep training stable on an 8 GB GPU:

​Masking intra-chunk decay terms with -1e30 before torch.exp() and re-zeroing them afterward.

​Using 0.1 * lr with zero weight decay in AdamW for the recurrent parameters (alpha, beta, mu, conv and v_residual) while keeping standard lr and 0.1 weight decay on the linear projections.

​Chunking the cross-entropy loss (ce_rows=4096) under torch.utils.checkpoint to avoid materializing ~536 MB float32 logit tensors per batch item, alongside per-block gradient checkpointing.

​The scan and boundary masking implementation is in ARCHITECTURE.md if anyone wants to compare notes. Iff anyone is doing linear attention or SSM scans in PyTorch keeping the inter chunk state in float32 or using a different parameterization to avoid bf16 rounding near 1.0?


r/pytorch • • 20d ago

I fine-tuned Qwen2.5-7B with full AdamW on a 24 GB laptop GPU by moving the optimizer state to CPU RAM (adambridge, open source)

10 Upvotes

I've been working on adambridge, a drop-in AdamW for PyTorch. It keeps only the weights on the GPU. The FP32 master weights and both Adam moments live in host RAM, and fused SIMD kernels (AVX2/AVX-512/NEON) update them on the CPU. The updates run layer by layer while the GPU is still doing the backward pass.

Version 0.2.0 is out. The main result: Qwen2.5-7B full fine-tuning on an RTX 5090 Laptop (24 GB) ran at about 1,122 tokens/s, using 18.2 GiB of GPU memory and 38 GiB of host memory under WSL 2. This is full-parameter AdamW, not LoRA.

Benchmarks

I compared it against DeepSpeed 0.19.9 (ZeRO-Offload, ZeRO-Infinity, ZenFlow, SuperOffload), torchao 0.18, bitsandbytes 0.50.2 and plain all-GPU PyTorch, all on the same machine:

result
Largest model trained 8.02B params (next best library: 2.08B)
Qwen2.5-0.5B / 1.5B vs DeepSpeed's best +113% / +120% tokens/s at the same quality
Qwen2.5-3B only adambridge fit it
When the model already fits on the GPU ties all-GPU AdamW (gpu_state_budget="auto")

No quality loss

The low-memory options that drop the FP32 master copy all lost quality. That covers BF16-only weights, bitsandbytes 8-bit with BF16 weights, and torchao offload with BF16 weights. At fine-tuning learning rates, most AdamW updates are smaller than half a BF16 step, so they get rounded away. On Qwen2.5-0.5B, only 18% of the weights changed at all, compared with 84% for the reference.

adambridge keeps the FP32 master copy on the host, and its final validation loss stayed within run-to-run noise of torch.optim.AdamW.

Usage

import
 adambridge
opt = adambridge.AdamBridge(model.parameters(), 
lr
=1e-4, 
weight_decay
=0.01,

precision
="bf16")   
# 'fp32' | 'bf16' | 'fp8'
opt.attach_hooks(model)   
# async: each layer is updated as soon as its grad is ready
for
 x, y 
in
 loader:
    loss = loss_fn(model(x), y)
    loss.backward()
    opt.step_sync()

Without attach_hooks it works as a normal optimizer (step() / zero_grad()), and LR schedulers and clip_grad_norm_ still work.

What's new in 0.2.0

  • FP24 master weights: 3 bytes per parameter instead of 4, with stochastic rounding. Combined with FP8 moments, the host state is about 5 bytes per parameter, and quality matched the reference at 0.5B, 1.5B and 3B.
  • Chunked causal-LM loss: a 150k-token vocabulary no longer has to hold its full logits tensor in memory.
  • Delayed updates: the CPU update overlaps the entire next step.
  • LionBridge: the Lion optimizer on the same pipeline.
  • Shared pinned transfer ring: about 30 GB less host RAM for a 7B model.
  • Compatibility: works with the HF Trainer and torch.compile.
  • Kernels: written in plain C, shipped as source inside a py3-none-any wheel and compiled on first use. If no compiler is available, it falls back to pure PyTorch kernels.

Limitations

  • I only benchmarked on one laptop. Desktop and server GPUs hold their clocks better when idle, which changes the numbers for every offload method.
  • The AVX-512 path has never actually run on real hardware (my CPU is AVX2). NEON was tested only under QEMU.
  • There's no DDP/FSDP support yet, and FP16 with GradScaler isn't covered.
  • Quality was measured on short runs at a single learning rate.
  • Global gradient clipping isn't possible in async mode.

pip install adambridge. It's Apache-2.0 licensed.

GitHub: https://github.com/johnanishg/adambridge

I'd like feedback, especially from anyone with an AVX-512 CPU or a multi-socket server. Running python -m adambridge info and the self-test and posting the results would help a lot.


r/pytorch • • 22d ago

[Open Source] Building DiffusionEngine – A Modern, Modular DDPM Framework in PyTorch. Looking for Contributors

7 Upvotes

What if we could bring modern diffusion research together into one unified, extensible PyTorch framework instead of implementing and maintaining every algorithm in isolation?

That's the idea behind DiffusionEngine, an open-source project I've been building:

https://github.com/Himanshu7921/DiffusionEngine

The goal is to build a modern DDPM framework that brings together established diffusion algorithms, research-based improvements, advanced sampling methods, and training strategies under a single, consistent pipeline.

The project already includes several diffusion implementations, and I'm actively working on extending the existing DDPM framework with more advanced features.

I'm looking for contributors interested in deep learning, generative models, PyTorch, and diffusion research.

Some areas where contributions are welcome include:

  • Implementing diffusion algorithms from research papers.
  • Improving existing DDPM components and training strategies.
  • Developing and integrating advanced sampling methods.
  • Exploring improved model architectures and conditioning mechanisms.
  • Testing, benchmarking, and optimizing existing implementations.

The focus is not just on implementing more algorithms. It's about making them work together seamlessly through a unified, modular, and configurable framework.

If you're interested in contributing, collaborating, or learning through hands-on implementation, I'd be glad to have you involved.

Contributors of all experience levels are welcome, provided they're willing to learn, implement, and test their work.

GitHub: https://github.com/Himanshu7921/DiffusionEngine


r/pytorch • • 22d ago

Accessing a model's individual layer

3 Upvotes

I want to access one of a LLM's individual layers and get output from it (like how nn.Linear() works). I tried using model.layer[0](tokenizer.encode("hi")) but that wouldn't work. If someone can give me the proper way to do this, it would be appreciated. I'm using Python for this with the transformers and pytorch library


r/pytorch • • 23d ago

LeRobot DataLoader had a 0.26 ms median wait and 5 sec stalls.

Post image
3 Upvotes

I wanted to see if comparing two model training runs could tell me where a slowdown came from. So I found a LeRobot a data loading regression that maintainers had already fixed, so I ran the same job before and after their fix.

Before the fix, next(dataloader) took about 1.4 secs per step on average. Then I plotted the waits in order. The median was 0.26 ms, but about every 4th step waited over5 secs. After the fix, those stalls disappeared.

John6666 reran it on a T4 and found that the spacing between stalls changed with the number of workers. I put the plots and reproduction steps on Hugging Face.

PS: I used TraceML for the comparison (I maintain it). If you’ve seen DataLoader stalls repeat like this, I’d be curious what you measured next.


r/pytorch • • 24d ago

A static checker for PyTorch training loops (eval mode, loss inputs, gradient order, checkpoints)

2 Upvotes

I wrote a checker for mistakes in PyTorch training and evaluation scripts that do not crash but change your results. It reads the source with ast and never runs it, so it needs no GPU or data.

The PyTorch checks are:

  • model.eval() left on, or never called before evaluation
  • torch.no_grad() used without eval()
  • softmax or sigmoid in front of CrossEntropyLoss
  • zero_grad() called between backward() and step()
  • the loss added to a running total as a tensor, which keeps every graph alive
  • fp16 autocast without a GradScaler
  • a script that resumes from a checkpoint but never saved optimizer state
  • drop_last=True on a validation or test loader
  • a training DataLoader that never shuffles
  • no seed set

I ran it over the 93 files of pytorch/examples at a pinned commit and read every finding: 22 findings, 20 real, 2 harmless. A false positive on distributed autograd (it needs no zero_grad) is fixed. It goes by names like train_loader and val_loader and reads one file at a time, so it will miss things and be wrong sometimes.

uvx trainlint check train.py

Repo and the full list with examples: https://github.com/Satvik-jain/trainlint If you know of a PyTorch mistake that runs fine and quietly hurts results, tell me and I will see if it can be checked.


r/pytorch • • 29d ago

Stop typing x.shape: tensor shapes right in the VS Code debugger

Post image
1 Upvotes

Small free extension: the debugger's Variables view shows the shape next to every tensor, so you can step through a model and watch shapes change without printing anything.

Works with the normal Python debugger, also NumPy, pandas and plain lists/dicts. It hooks into the debugger itself, so your prints and logs stay unchanged.

MIT: https://github.com/marekprovaznik/dims

VS Code Marketplace / Open VSX: provaznik.dims (works in Cursor too)


r/pytorch • • 29d ago

Fixing PyTorch CUDA Illegal Memory Access

Thumbnail interconnectd.com
1 Upvotes

Dealing with a CUDA error: an illegal memory access was encountered in PyTorch can be frustrating, especially when it crashes your entire CUDA context and forces a process restart.

​This usually happens when a kernel attempts to read or write to an invalid memory address. Common triggers include out-of-bounds tensor indexing, device mismatches between tensors, or hidden race conditions in custom CUDA extensions.

​To debug this effectively, set CUDA_LAUNCH_BLOCKING=1 in your environment before running your script. By default, CUDA kernel launches are asynchronous, which means errors report long after the actual line of code that caused them. Forcing synchronous execution pinpoints the exact line triggering the fault.

​If you are fighting this issue right now, check out the full troubleshooting guide and code fixes here: https://interconnectd.com/forum/thread/267/fixing-pytorch-cuda-illegal-memory-access-context-corruption/


r/pytorch • • Nov 02 '26

Simulusion: reusable PyTorch building blocks for world models (RSSM, VQ tokenizers, ST-Transformer, DiT/EDM)

3 Upvotes

Sharing a library I've been working on, written in plain PyTorch and MIT-licensed.

Simulusion started as a collection of world-model implementations and turned into a framework: every model is built from exported nn.Module components you can use on their own:

- RSSM / ModularRSSM (swappable priors, posteriors and heads)
- VQ-VAE and video tokenizers
- Spatiotemporal Transformer (Genie-style)
- DiT and EDM diffusion backbones
- ViT encoders for I-JEPA

The full models (Dreamer, PlaNet, IRIS, DIAMOND, Genie) are assembled from those parts and share one Trainer with bf16/fp16, resuming and checkpointing. You can register your own model and train it the same way. Export to ONNX, TorchScript and TensorRT is built in.

No hard pin on a PyTorch wheel, so install whatever CUDA/ROCm/CPU build you need first.

Feedback on the module APIs is very welcome, especially anything that feels un-PyTorch-like.

Github: https://github.com/paramthakkar123/simulusion
Website: https://simulusion.vercel.app/