FlashAttention is a high-performance library implementing IO-aware exact attention for transformer models, with CUDA kernels targeting NVIDIA Ampere (SM80), Hopper (SM90), and Blackwell (SM100) architectures, plus a Python CuTe DSL implementation (FA4), a Composable Kernel backend for AMD, and Triton fallbacks. The library exposes PyTorch-integrated Python APIs (flash_attn_func, flash_attn_varlen_func, flash_attn_with_kvcache) backed by custom CUDA extensions with autograd support. It also ships fused ops (dense layers, layer norm, cross-entropy), model definitions with HuggingFace state-dict remapping (GPT, BERT, LLaMA, Falcon, Baichuan, OPT, GPT-J, GPT-NeoX, ViT), and a PyTorch Lightning + Hydra training pipeline for GPT-style models. The dominant character is a systems library, though it has a hybrid research flavor: experimental kernels for unreleased hardware, benchmark suites, and a training sub-package all coexist in one monorepo. The architecture is a layered monolith: a Python API layer dispatches to multiple kernel backends (CUDA C++ for FA2, CUTLASS/CuTe for FA3, Python CuTe DSL for FA4, CK for AMD, Triton for portability). The core algorithmic contributions are the online softmax with rescaling, tiled attention with shared-memory staging, warp-specialized producer/consumer pipelines using TMA and GMMA, persistent tile schedulers, and deterministic backward passes with semaphore-based reductions. The training sub-package is a secondary component demonstrating the kernels in full GPT training runs with tensor/sequence parallelism. The codebase is actively maintained with extensive CI/CD (including Apptainer-based FA4 CI), a large test suite covering correctness against reference implementations and HuggingFace models, and performance benchmarks. However, it carries significant complexity: multiple overlapping backends with duplicated logic and inconsistent feature support, a complex build system with many environment variables, a monolithic gpt.py model file, and deprecated components (csrc/layer_norm is explicitly deprecated in favor of Triton). The kernel code is world-class and worth studying; the surrounding infrastructure is functional but organically grown.
Presidio is a production-grade PII detection and anonymization framework. It operates as both a Python library and a set of microservices (Flask REST APIs) for detecting and redacting personally identifiable information (PII) in text, images (including DICOM), and structured/tabular data. The system is built around three core engines: the Analyzer (entity recognition via regex patterns, NLP models, and LLMs), the Anonymizer (applies operators like replace, redact, mask, hash, encrypt), and the Image Redactor (OCR-based text extraction and bounding-box redaction). A CLI tool and a structured data engine complement the main services. The architecture is modular and extensible: recognizers are pluggable (predefined regex-based, NLP-based, or custom), anonymization operators follow a consistent interface, and NLP engines (spaCy, Stanza, Transformers, GLiNER, HuggingFace) are swappable via YAML configuration. The system supports context-aware detection, score thresholds, allow/deny lists, and batch processing. External dependencies include NLP libraries, OCR (Tesseract), cloud services (Azure AI Language, Azure Health Data Services), and LLM providers (Azure OpenAI, Ollama). Key entry points include the AnalyzerEngine.analyze() method, AnonymizerEngine.anonymize(), the REST endpoints (/analyze, /anonymize, /redact), and the presidio-cli command-line tool. The primary data flow is: input text/image → Analyzer (detects entities with scores) → Anonymizer (applies operators) → output. For images, OCR extracts text before analysis. The system is designed for compliance with data privacy regulations (GDPR, HIPAA, etc.) and is used in production deployments with Kubernetes, Azure, and Spark.
vit-pytorch is a comprehensive PyTorch library implementing dozens of Vision Transformer (ViT) architectures and extensions, along with self-supervised pretraining methods (MAE, DINO, SimMIM, MP3, LeJEPA) and video transformers (ViViT, NaViT-3D, CCT-3D). It is a research-oriented codebase offering a consistent API across models, all accepting standard hyperparameters like image_size, patch_size, depth, and heads. The library covers a wide spectrum of attention mechanisms (cross-attention, shifted windows, channel attention, sparse gating), tokenization strategies (patch merging, region-based, t2t, SPT), and training utilities (recorders, extractors, distillation wrappers). While primarily a collection of model implementations, it also includes action transformers for robotics (VAT, VAAT) and N-dimensional ViTs, demonstrating both breadth and depth of recent transformer research. The code is highly modular, relying on shared building blocks such as Attention, FeedForward, and Transformer classes, with heavy but well-organized use of einops for tensor manipulation. Some variants are experimental and may lack the polish of the core models, but the overall architecture is clean and serves as a valuable reference for implementing and comparing ViT variations. The repository is actively maintained, with recent commits and a large user base, but its sheer size and variety mean that not every model is exhaustively tested—core components are covered by basic forward-pass tests, while many advanced variants rely on the underlying patterns being sound.
OpenRLHF is a production-oriented distributed RLHF/RL training framework for large language models, not a research notebook collection. The codebase implements a full training stack: SFT, reward modeling, DPO/IPO/cDPO, and RL algorithms including PPO, REINFORCE++, GRPO, RLOO, Dr.GRPO, and FlashREINFORCE. Its architecture combines Ray for distributed actor orchestration and placement groups, vLLM for high-throughput rollout generation, DeepSpeed ZeRO for model training, and HuggingFace Transformers for model handling. The primary entry points are CLIs under openrlhf/cli, with train_ppo_ray.py as the main RL launcher; these accept a large set of hierarchically parsed dotted flags that control training, rollout, reward, vLLM, and DeepSpeed behavior. The repository is genuinely hybrid in spirit because it trains research-scale models and reproduces academic methods, but its dominant character is application/framework: it ships packaging, Dockerfiles, CLI entry points, unit tests, and versioned releases. The design emphasizes a token-in-token-out agent abstraction that unifies single-turn and multi-turn RLHF, plus sync and async training modes, a hybrid engine that colocates training and generation on shared GPUs, and VLM support. Distributed checkpointing, LoRA/QLoRA, packing, dynamic batch sizing, importance sampling corrections, and KL-estimator variants are all present in the code, not merely in the README. Craftsmanship is strong. The code separates concerns across cli/, trainer/, models/, datasets/, and utils/, and includes several genuinely reusable patterns such as a self-contained math answer grader, a flat-to-hierarchical argparse config converter, a typed RL experience dataclass, and distributed loss-normalization utilities. The test suite exercises loss estimators, trainer control flow, experience batching, and agent behavior with mocked heavy dependencies, which is a pragmatic way to test GPU-bound code on CPU. The main weaknesses are operational rather than architectural: dependencies are extremely tightly pinned (deepspeed==0.19.6, transformers==5.15.0, ray==2.55.0, vllm==0.29.0), and the code monkey-patches upstream internals and relies on version-specific behaviors. This makes upgrades brittle, and the CI pipeline builds wheels without running the test suite. Overall, this is a mature, actively maintained framework with high reusability for engineers building LLM alignment pipelines, though it demands GPU infrastructure and careful dependency alignment.
LLaMA-Factory is a production-grade, unified framework for fine-tuning, evaluating, and serving 100+ large language and multimodal models. It provides a CLI (`llamafactory-cli`), a Gradio web UI (LLaMA Board), and an OpenAI-compatible API server. The architecture is monolithic but highly modular, built on Hugging Face Transformers/TRL/PEFT with optional integration of vLLM, SGLang, DeepSpeed, FSDP, Megatron Bridge, and hardware-specific backends (CUDA, ROCm, NPU, XPU). Training pipelines support full-parameter, LoRA, QLoRA, freeze-tuning, and alignment methods (DPO, PPO, KTO, etc.) with extensive data processing (multimodal, packing, streaming, template-based formatting). The codebase features a plugin system (v1) for kernels, quantization, distributed backends, and batching strategies, though it maintains a parallel legacy (v0) path. Reusable components include dataset processors, chat template hierarchy, multimodal plugin architecture, custom trainer callbacks, and batching strategy plugins. While the framework is actively maintained and well-tested, it suffers from some technical drift due to a dual-codebase structure, hardcoded model registries, version pinning, and fragile monkey-patching in distributed integrations.
This repository is an unofficial PyTorch implementation of the Titans architecture from the research paper 'Titans: Learning to Memorize at Test Time'. It provides a library of neural network modules including Neural Memory, Memory-as-Context Transformer, and various attention mechanisms. The codebase consists of modular components that can be used as building blocks for sequence modeling, with training scripts demonstrating language modeling on the enwik8 dataset. The implementation focuses on test-time training mechanisms where the model learns to memorize at inference time through a neural memory module that updates its weights based on incoming sequences.
This repository is the official companion code for the book *Build a Large Language Model (From Scratch)* by Sebastian Raschka (105k+ stars). It provides a step-by-step, educational implementation of GPT-2 and its modern variants (Llama 3, Qwen3, Gemma 3/4, Olmo3) entirely in PyTorch, organized by book chapters (2–7 plus appendices). The codebase is a mix of Jupyter notebooks for interactive learning and Python modules that form a reusable pip package (`llms-from-scratch`), accompanied by extensive CI/CD pipelines, unit tests, and performance analysis scripts. Architecturally, the core is a modular transformer library that includes tokenization (BPE, tiktoken, custom), multi-head attention with multiple variants (GQA, MLA, SWA, DSA, cross-layer KV sharing), feedforward blocks, normalization (LayerNorm, RMSNorm), and LoRA. The code supports pretraining from scratch, classification finetuning (spam, IMDB), instruction finetuning (with/without LoRA), and preference tuning (DPO). It can load pretrained weights from OpenAI, Hugging Face, and local checkpoints. The package exposes clean interfaces (`GPTModel`, `generate`, `train_model_simple`) and includes bonus materials for KV cache implementations, mixture-of-experts, memory estimators, and user interfaces (Chainlit). While primarily educational, the code exhibits production-quality patterns: isolated attention modules, configurable model architecture, well-structured training loops, and robust weight loading with shape validation. The repository is actively maintained with recent commits, cross-platform support (Linux, macOS, Windows), and a strong emphasis on reproducibility (fixed seeds, deterministic settings, environment definitions via pixi/uv/conda). Duplication exists across bonus notebooks and a few hardcoded paths, but the core package and test suite are well-coordinated.
LightGlue is a PyTorch library for local feature matching between image pairs. It implements a deep neural network that takes sparse keypoints and descriptors (extracted by models like SuperPoint, DISK, ALIKED, or SIFT) and outputs correspondences. The architecture uses stacked self- and cross-attention transformer layers with adaptive pruning (width and depth) for speed, achieving state-of-the-art accuracy at high throughput. The repository provides pretrained weights, a benchmark script, and a demo notebook. It is designed for inference only; training code is in a separate repository (glue-factory). The code is well-structured, with clean separation between feature extractors, the matcher, and utility functions. It supports FlashAttention and PyTorch compilation for performance.
TinyLLaVA Factory is a modular Python framework for building, training, evaluating, and serving small-scale Large Multimodal Models (LMMs). It provides a pluggable architecture with separate components for vision towers (CLIP, SigLIP, DINOv2), language models (Phi, TinyLlama, Gemma, Qwen2, etc.), and connectors (MLP, QFormer, Resampler), all accessible via factory registries. The training pipeline supports two-stage pretraining (alignment) and finetuning with full, LoRA, or QLoRA recipes using DeepSpeed. It includes a comprehensive evaluation suite for standard benchmarks (VQA, GQA, SQA, POPE, MMMU, etc.) and a Gradio-based web demo. The codebase is well-organized and follows clean architectural patterns, though many modules are tightly coupled to the internal framework. It is actively maintained, with recent additions like a visualization tool and support for new models.
This is a comprehensive educational course repository ('Generative AI for Beginners') containing 21 structured lessons covering the full spectrum of generative AI application development. While classified as an application repository due to its extensive runnable code examples across Python, JavaScript, TypeScript, and .NET, its primary purpose is pedagogical. The repository teaches practical patterns for building GenAI applications including: prompt engineering, chat applications, RAG/vector search, image generation, function calling, AI agents, fine-tuning, LLMOps, and responsible AI practices. Each lesson provides assignments and solutions for multiple LLM providers (Azure OpenAI, OpenAI, GitHub Models). The codebase demonstrates modern GenAI application patterns with a strong emphasis on multi-language implementation parity and accessibility through 40+ language translations. The shared/python utilities provide reusable helpers for API interactions, environment management, and input validation that could be extracted for production use.
This repository is a comprehensive collection of annotated PyTorch implementations of deep learning papers, spanning transformers, GANs, reinforcement learning, diffusion models, and more. Each implementation includes side-by-side notes explaining the code and underlying concepts, making it an educational resource for understanding and reproducing paper results. The codebase is organized by paper/model type, with standalone experiment scripts, reusable modules, and configuration-driven training loops. Key strengths include clean abstractions for transformer components, a flexible configs system, and extensive coverage of both foundational and modern architectures. However, the project has not seen commits since early 2024, some dependencies are outdated, and certain experiments require large GPU resources or external data not bundled in the repo. While individual components are well-crafted and reusable, the overall collection is best used as a reference and learning tool rather than a production framework.
This repository is a structured, comprehensive AI engineering curriculum spanning 20 phases and over 500 lessons, from math foundations and ML fundamentals to deep learning, computer vision, NLP, speech, transformers, generative AI, reinforcement learning, LLMs from scratch, agent engineering, multi-agent systems, production infrastructure, and ethics/safety. It is an educational resource, not a production application or data research project. The code consists of self-contained pedagogical implementations (primarily Python, with some TypeScript, Rust, and Julia) that demonstrate core algorithms from scratch—such as attention mechanisms, BPE tokenization, diffusion models, RLHF, and agent loops—using synthetic data and deterministic stubs. Capstone projects include small web servers (Hono/TypeScript) and test harnesses. The curriculum is actively maintained with CI tooling, certification prep materials, and translation support. While the code is simplified for learning, it exhibits clean patterns, consistent lesson structure, and testing practices that make individual components (e.g., tool registries, state machines, evaluation harnesses) reusable in other contexts.
PMetal is a comprehensive machine learning framework specifically optimized for Apple Silicon hardware. It provides a complete suite for LLM training, fine-tuning, inference, and deployment through multiple interfaces (CLI, TUI, GUI, Python SDK, and REST API). The framework leverages Apple-specific technologies like Metal GPU, ANE, and UltraFusion for performance optimization while supporting standard ML workflows including LoRA/QLoRA fine-tuning, knowledge distillation, model merging, and quantization to formats like GGUF. The architecture follows a modular workspace design with over 20 specialized crates handling different aspects of the ML lifecycle, unified through a job specification system and configuration framework.
Thonburian Whisper is a Thai Automatic Speech Recognition (ASR) model fine-tuned from OpenAI's Whisper, provided as a reusable application with associated tools. The repository offers the pre-trained model hosted on Hugging Face, along with utilities for transcription, long-form audio processing, TensorRT conversion, and evaluation. Key components include a CLI tool for long-form transcription using VAD and syllable segmentation, scripts for converting the model to TensorRT format for efficient inference, and evaluation metrics calculation. The architecture consists of modular Python scripts and notebooks that demonstrate usage rather than a monolithic application, with clear separation between model usage, audio preprocessing, and post-processing.
Promptify is a Python library for performing NLP tasks using large language models (LLMs) with structured, type-safe outputs. It provides a scikit-learn-like interface where users instantiate task classes (e.g., NER, Classify, QA, Summarize) and call them with plain text. The library uses LiteLLM as a universal backend to support 100+ providers (OpenAI, Anthropic, Ollama, etc.), Pydantic v2 for output schemas, Jinja2 for prompt templates, and tenacity for retries. Architecture follows a clean separation: Task classes (promptify/tasks) build prompts via PromptBuilder, send them via LLMEngine (which wraps LiteLLM), and parse responses via a safe Parser that never uses eval(). The package also includes a built-in evaluation framework (promptify/eval) with metrics for precision, recall, F1, accuracy, exact match, and ROUGE, plus dataset loading utilities. The code is well-structured, typed, and includes comprehensive tests. The primary artifact is the "promptify" Python package, installable via pip. The repository is not a data research project; it is a software library for developers.
Audiocraft is a research codebase from Meta (Facebook Research) for state-of-the-art audio generation, including MusicGen, AudioGen, MAGNeT, JASCO, MultiBand Diffusion, and AudioSeal watermarking. It provides training and inference pipelines for text-to-music, text-to-sound, music continuation, style transfer, and symbolic conditioning (chords, drums, melody). The repository is primarily a research library with extensive configuration-driven training (Hydra/Dora), evaluation metrics (FAD, KLD, CLAP, ViSQOL), and interactive Gradio demos. It is not a production application but a collection of models, solvers, and utilities for audio generation research. The codebase is well-structured with modular components (conditioners, codebook patterns, audio effects) and includes unit tests, but relies on internal datasets and cluster paths that limit full reproducibility. Pretrained models are available via HuggingFace Hub for inference.
Xinference is a production-grade model serving platform that provides OpenAI-compatible REST APIs for a wide range of AI models including LLMs, embeddings, rerank, image generation, video, audio/TTS, and world models. It supports multiple inference backends (vLLM, SGLang, transformers, MLX, llama.cpp) and can be deployed as a single process or a distributed cluster using an actor-based supervisor/worker architecture (xoscar). The system includes a web UI for model management, authentication/authorization with OAuth2 scopes, token-aware routing for load balancing, and monitoring capabilities. It bundles many third-party model implementations for turnkey deployment, which reduces setup friction but introduces maintenance overhead from vendored code. The architecture is a hybrid of a monolithic FastAPI server and a distributed actor system. Key entry points are CLI commands (xinference, xinference-supervisor, xinference-worker) and the REST API. The frontend is a Next.js application statically exported and served by the backend. The codebase demonstrates strong patterns in modular route registration, plugin-style model registries, and streaming response handling, but also carries significant technical debt from heavy vendoring, duplicated code across third-party integrations, and version-sensitive patches to upstream libraries like vLLM.
This is a research-grade PyTorch implementation of Danijar Hafner's Dreamer v4 model-based reinforcement learning algorithm. The core artifact is the `dreamer4` package, dominated by a monolithic `dreamer4/dreamer4.py` (~3000 lines) that implements `VideoTokenizer`/`SpaceTimeTokenizer`, `DynamicsWorldModel`, `AudioTokenizer`, and `StateTokenizer`. These classes build causal space-time transformers with separate space/time attention blocks, latent flow-matching diffusion with shortcut consistency, BYOL-style tokenizer pre-training, PoPE attention, and a large zoo of experimental loss terms (latent autoregressive loss, decorrelation, orthogonality, SigReg, self-flow distillation, shortcut loss). `dreamer4/trainers.py` provides training loops (VideoTokenizerTrainer, BehaviorCloneTrainer, DreamTrainer, SimTrainer) and `dreamer4/cli.py` exposes CLI entry points for training and serving the world model. The repository is hybrid: primarily research code, but packaged and tested like a library. It ships a pyproject.toml with pinned dependencies, a parametrized test suite (tests/test_dreamer.py, test_e2e.py, test_env_wrapper.py), a browser-based Snake environment with a Flask-style server (`dreamer4/web_env/`) used for human demonstration collection and replay-buffer inspection, and environment wrappers in `dreamer4/env.py` that record agent experience to folders or memmap replay buffers. Root-level scripts are the actual experiment entry points, targeting standard benchmarks: HalfCheetah (imagination RL), CartPole (dynamics + RL), MovingMNIST (tokenizer + dynamics), and Snake (PPO with dynamics model). Craftsmanship is above typical research code: clean package layout, pytest coverage across many hyperparameter combinations, self-contained utilities (LossNormalizer, tensor pack/unpack helpers, with_seed decorator, memmap replay-buffer helpers), and HuggingFace Accelerate integration for distributed/mixed-precision training. However, the single-file core, 100+ hyperparameter flags on trainers, scattered hard-coded constants, sparse docstrings, and reliance on volatile niche packages (x-transformers, h-net-dynamic-chunking, PoPE_pytorch, adam-atan2-pytorch) make long-term stability and code reuse risky. The repository is recently committed and appears maintained, but it is explicitly beta-status experimental research code, not a production system.
This repository is the official implementation of the SANA family of diffusion models for high-resolution image and video generation, developed by NVIDIA Research. It is primarily a research codebase, containing training and inference pipelines for multiple model variants: SANA (text-to-image), SANA-1.5, SANA-Sprint (few-step distillation), SANA-Video, SANA-Video 2.0, SANA-Streaming (long video), LongSANA, and SANA-WM (world model for camera-controlled video). The codebase also includes post-training with reinforcement learning (Sol-RL), ControlNet support, and various schedulers (flow matching, DPM-Solver, LCM, self-forcing). While the core purpose is research, the repository also provides deployable Gradio applications, conversion scripts to Hugging Face diffusers format, and integration with ComfyUI and SGLang, giving it a hybrid application character. The code is heavily optimized with custom Triton kernels for efficient attention (LiteMLA, Gated Delta Net) and includes distributed training utilities (FSDP, context parallelism). The repository is actively maintained with frequent commits and supports a wide range of model sizes (600M to 14B parameters).
This repository is a curated collection of Jupyter notebooks implementing core components of modern LLM architectures, intended for interview preparation. It covers attention mechanisms (MHA, GQA, MLA, KV-cache), normalization layers (LayerNorm, RMSNorm), functional components (RoPE, SwiGLU, LoRA, BPE, activation functions, cross-entropy, InfoNCE, sampling, quantization, SFT loss, tool calling parsing), and reinforcement learning losses (DPO, GRPO, DAPO, GSPO, KL divergence). Each notebook is a self-contained, minimal implementation of a specific algorithm, typically using PyTorch. The code is clean, concise, and well-commented, reflecting good engineering practices for educational purposes. While the repository is not a production application and lacks data pipelines, model training scripts, or continuous integration, it serves as a high-quality reference for understanding and reproducing the mathematical foundations of transformer-based language models. The hybrid nature lies in its focus on research-oriented ML components, but its structure is a pure code library rather than a data-driven research project.