agentleFS
MicrosoftKnown publishermicrosoft/onnxruntime-genai/.github/copilot-instructions.md

onnxruntime-genai

Copilot instructions1.1k starsChanged 3 months agoMITView on GitHub

This is ONNX Runtime GenAI, a high-performance inference library for generative AI models. The codebase implements the complete generative AI loop including preprocessing, ONNX Runtime inference, logits processing, search/sampling, and KV cache management. The State class hierarchy in src/models/model.h handles device-specific execution, while the Engine class in src/engine/ manages request batching and scheduling. WinML builds require explicit SDK version specification: WinML integration downloads Microsoft.Windows.AI.MachineLearning via NuGet and copies headers/libs to a local ort/ directory. Each hardware backend implements DeviceInterface (defined…

Trending

Quiet since September.about the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 1 mentionApr 2026: 2 mentionsMay 2026: 9 mentionsJun 2026: 10 mentionsJul 2026: 0 mentionsAug 2026: 3 mentionsSep 2026: 1 mentionOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the microsoft/onnxruntime-genai repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about microsoft/onnxruntime-genai

The biggest 5 of 29 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 29

Talked about on GitHub (29 times).

On GitHub · 29

24 more on GitHub

The file

We split this copilot-instructions.md into the rules it gives an agent

3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use OgaCheckResult() wrapper for C API error propagation:

    line 94
  2. Very specific:

    Always test with actual model files from test/models/ directory rather than mock data.

    line 163
  3. Distinctive:

    When reviewing those files, prioritize these model-builder rules over generic guidance and flag violations explicitly.

    line 175

≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
copilot-instructions.md

ONNX Runtime GenAI - AI Coding Agent Instructions

Architecture Overview

This is ONNX Runtime GenAI, a high-performance inference library for generative AI models. The codebase implements the complete generative AI loop including preprocessing, ONNX Runtime inference, logits processing, search/sampling, and KV cache management.

Core Components

  • src/models/ - Model implementations with support for LLMs, VLMs (Vision), ALMs (Audio), and Pipeline models
  • src/engine/ - Request batching engine for concurrent model execution with dynamic scheduling
  • src/generators.h - Central generator logic coordinating the full inference pipeline
  • src/ort_genai.h - Zero-cost C++ wrapper around the C API for automatic resource management
  • Language bindings: Python (src/python/), C# (src/csharp/), Java (src/java/), Objective-C (src/objectivec/)

Key Abstractions

// Core inference flow: Model -> Generator -> Tokenizer
auto model = OgaModel::Create("phi-2");
auto tokenizer = OgaTokenizer::Create(*model);
auto generator = OgaGenerator::Create(*model, params);

The State class hierarchy in src/models/model.h handles device-specific execution, while the Engine class in src/engine/ manages request batching and scheduling.

Build System & Development Workflow

Primary Build Commands

# Cross-platform Python build script (preferred)
python build.py --config Release --use_cuda --build_java --enable_tests

# Platform-specific scripts
build.bat         # Windows batch
build.sh          # Linux/Mac shell

Key Build Options (cmake/options.cmake)

  • USE_CUDA/USE_DML - Hardware acceleration backends
  • USE_WINML - Windows ML integration requiring WINML_SDK_VERSION parameter
  • ENABLE_JAVA/ENABLE_PYTHON - Language binding compilation
  • USE_GUIDANCE - Constrained generation support

WinML Build Pattern

WinML builds require explicit SDK version specification:

# WinML build - WINML_SDK_VERSION is mandatory
python build.py --use_winml -DWINML_SDK_VERSION=2.1.1

WinML integration downloads Microsoft.Windows.AI.MachineLearning via NuGet and copies headers/libs to a local ort/ directory.

Testing

# Python tests with test models
python -m pytest -sv test_onnxruntime_genai_api.py -k "test_name" --test_models ..\models

# C++ unit tests via CMake/CTest
ctest --build-config Release --output-on-failure

Code Patterns & Conventions

Device Interface Pattern

Each hardware backend implements DeviceInterface (defined in src/smartptrs.h):

struct CudaInterface : DeviceInterface {
  std::unique_ptr<DeviceBuffer> Allocate(size_t size) override;
  void CopyToDevice(DeviceSpan<T> dst, std::span<const T> src) override;
};

Model State Management

Models follow the State pattern where each model type extends the base State class:

struct State {
  virtual DeviceSpan<float> Run(int total_length, 
                               DeviceSpan<int32_t>& next_tokens) = 0;
  virtual void RewindTo(size_t index) {}  // For session continuation
};

Error Handling Convention

Use OgaCheckResult() wrapper for C API error propagation:

OgaCheckResult(OgaCreateModel(model_path, &model));  // Throws std::runtime_error

Memory Management

  • DeviceSpan/DeviceBuffer: Device-agnostic memory abstractions
  • std::unique_ptr with custom deleters: For C API resource cleanup
  • LeakChecked<T>: Debug-mode leak detection for core types

Critical Integration Points

ONNX Runtime Dependency Management

ADO pipelines obtain ORT lib/headers via three methods:

  1. Explicit ORT_HOME - Pipeline provides pre-built ORT artifacts (preferred)
  2. Auto-download via CMake - cmake/ortlib.cmake fetches from ORT-Nightly feed when ORT_HOME unset
  3. Python build driver - tools/python/util/dependency_resolver.py downloads NuGet packages

Model Loading Pipeline

  1. Config parsing (src/config.cpp) - Reads genai_config.json model metadata
  2. ONNX session creation via onnxruntime_api.h wrappers
  3. Device interface selection based on provider availability
  4. KV cache initialization (src/models/io/kv_cache.cpp) for transformer models

Multi-Modal Support

Vision models (Phi-Vision) use separate processor classes:

  • PhiImageProcessor - Image tokenization and preprocessing
  • MultiModalProcessor - Coordinates text/image inputs

Execution Provider Detection

Hardware acceleration auto-detection follows this priority:

  1. CUDA (if USE_CUDA=ON and CUDA runtime available)
  2. DirectML (Windows, if USE_DML=ON)
  3. CPU fallback

Project-Specific Gotchas

Windows-Specific Build Requirements

  • Visual Studio 2022 required for C++20 features
  • WinML integration requires specific NuGet package versions (see cmake/nuget.cmake)
  • Cross-compilation for ARM64/ARM64EC supported via CMake platform flags

Model Compatibility Matrix

The repo supports specific model architectures - check src/models/model_type.h for the canonical list. New models require:

  1. Config template in model directory
  2. State implementation extending base State class
  3. Optional custom processors for multi-modal inputs

Performance Considerations

  • KV caching is automatically managed but can be configured via src/runtime_settings.cpp
  • Continuous decoding (session continuation) requires careful state management
  • Multi-LoRA adapters use separate weight loading in src/models/io/adapters.cpp

Testing Strategy

Tests are organized by language binding:

  • C++ tests: test/ directory, focused on core API validation
  • Python tests: test/python/, includes end-to-end model testing
  • Platform tests: Android/iOS tests run via emulator/simulator

Always test with actual model files from test/models/ directory rather than mock data.

Model Builder Review Rules

For any pull request that modifies files under src/python/py/models/**, reviewers and Copilot must apply:

  • .github/instructions/python-model-builder.instructions.md
  • src/python/py/models/README.md
  • src/python/py/models/DESIGN.md
  • src/python/py/models/loaders/LOADERS.md
  • src/python/py/models/quantization/QUANTIZATION.md

When reviewing those files, prioritize these model-builder rules over generic guidance and flag violations explicitly.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.