tripy-constraints

작성자: nvidia

nvtripy 연산에 대한 선언적 제약 DSL을 사용한 작성자 입력/출력 제약 조건. 사용 시점: input_requirements 또는 output_guarantees 정의 시,…

npx skills add https://github.com/nvidia/tensorrt-incubator --skill tripy-constraints

Authoring Constraints for nvtripy Operations

When to Use

  • Defining type constraints for a new or existing operation
  • Writing input_requirements or output_guarantees for @wrappers.interface
  • Debugging constraint validation errors at runtime
  • Understanding auto-type-casting behavior

Architecture Overview

The constraint system lives in nvtripy/frontend/constraints/ and consists of:

  • Fetchers (fetcher.py): Extract values from function arguments or return values
  • Logic (logic.py): Compose constraints with boolean operators
  • Base (base.py): Abstract base class for all constraints
  • Wrappers (nvtripy/frontend/wrappers.py): The @interface decorator that applies constraints

Core Components

Fetchers — Extracting Values

from nvtripy.frontend.constraints import GetInput, GetReturn

# Get a function parameter by name
GetInput("input")           # The parameter named "input"
GetInput("dtype")           # The parameter named "dtype"
GetInput("input").dtype     # The dtype of the "input" parameter (uses GetDataType)

# Get a return value by index
GetReturn(0)                # First return value
GetReturn(0).dtype          # Dtype of first return value

Logic — Composing Constraints

from nvtripy.frontend.constraints import OneOf, If, GetInput, GetReturn

# OneOf: value must be in a set
OneOf(GetInput("dtype"), [dt.float32, dt.float16, dt.bfloat16])

# Equal: two values must match
GetInput("weight").dtype == GetInput("input").dtype
GetReturn(0).dtype == GetInput("input").dtype

# NotEqual
GetInput("dtype") != None

# And: combine with &
OneOf(GetInput("input").dtype, [dt.float32, dt.float16])
& (GetInput("weight").dtype == GetInput("input").dtype)

# Or: combine with |
OneOf(GetInput("dtype"), [dt.float32]) | OneOf(GetInput("dtype"), [dt.float16])

# If: conditional constraint
If(
    GetInput("dtype") != None,                    # condition
    OneOf(GetInput("dtype"), [dt.float32]),        # then: applied when condition is true
    # else branch is optional
)

# Invert with ~
~OneOf(GetInput("dtype"), [dt.float32])  # dtype must NOT be float32

All Available Logic Classes

ClassUsageDescription
OneOf(fetcher, options)OneOf(GetInput("x").dtype, [dt.float32, dt.float16])Value must be in the list
EqualGetInput("a").dtype == GetInput("b").dtypeTwo values must be equal (created via ==)
NotEqualGetInput("dtype") != NoneTwo values must not be equal (created via !=)
Andconstraint1 & constraint2Both must be satisfied (created via &)
Orconstraint1 | constraint2At least one must be satisfied (created via |)
If(cond, then, else_)If(GetInput("dtype") != None, then_constraint)Conditional constraint
AlwaysTrueAlwaysTrue()Always passes
AlwaysFalseAlwaysFalse()Always fails

Using @wrappers.interface

The @wrappers.interface decorator from nvtripy/frontend/wrappers.py accepts:

@wrappers.interface(
    input_requirements=<Logic>,       # Pre-execution: validate inputs
    output_guarantees=<Logic>,        # Post-execution: validate outputs
    convert_to_tensors=True,          # Auto-convert TensorLike to Tensor
    conversion_preprocess_func=None,  # Custom preprocessing before conversion
)
  • input_requirements: Checked BEFORE the function runs. If a dtype mismatch is found and auto-casting can fix it, the system will automatically cast inputs.
  • output_guarantees: Checked AFTER the function runs. Verifies the output properties match expectations.

Common Patterns

Simple dtype restriction

@wrappers.interface(
    input_requirements=OneOf(GetInput("input").dtype, [dt.float32, dt.float16, dt.bfloat16]),
    output_guarantees=GetReturn(0).dtype == GetInput("input").dtype,
)
def my_op(input: "nvtripy.Tensor") -> "nvtripy.Tensor":

Multiple inputs with matching dtypes

@wrappers.interface(
    input_requirements=OneOf(GetInput("input").dtype, [dt.float32, dt.float16, dt.bfloat16])
    & (GetInput("weight").dtype == GetInput("input").dtype)
    & (GetInput("bias").dtype == GetInput("input").dtype),
    output_guarantees=GetReturn(0).dtype == GetInput("input").dtype,
)
def layernorm(input, weight, bias, eps):

Optional dtype parameter

@wrappers.interface(
    input_requirements=OneOf(
        GetInput("input").dtype,
        [dt.float32, dt.float16, dt.bfloat16, dt.float8, dt.int8, dt.int32, dt.int64, dt.bool],
    )
    & If(
        GetInput("dtype") != None,
        OneOf(GetInput("dtype"), [dt.float32, dt.float16, dt.bfloat16, dt.int8, dt.int32, dt.int64, dt.bool]),
    ),
    output_guarantees=If(
        GetInput("dtype") != None,
        GetReturn(0).dtype == GetInput("dtype"),
        GetReturn(0).dtype == GetInput("input").dtype,
    ),
)
def ones_like(input, dtype=None):

Initializer ops (no tensor inputs, just dtype)

@wrappers.interface(
    input_requirements=OneOf(
        GetInput("dtype"), [dt.float32, dt.float16, dt.bfloat16, dt.int8, dt.int32, dt.int64, dt.bool]
    ),
    output_guarantees=GetReturn(0).dtype == GetInput("dtype"),
)
def ones(shape, dtype=dt.float32):

How Auto-Casting Works

When input_requirements include dtype constraints via OneOf:

  1. The system checks if all inputs satisfy constraints
  2. If a dtype mismatch is found, it looks for a valid target dtype from the OneOf options
  3. Inputs are automatically cast to the matching dtype before the function executes

This means users don't need to manually cast, e.g., tp.ones((2,), dtype=tp.float16) + tp.ones((2,), dtype=tp.float32) will auto-cast.

Constraint Error Messages

When constraints fail, the system generates an error like:

Expected 'input' to be one of [float32, float16, bfloat16] (but it was 'int32')

The error text comes from the __str__ and doc_str methods of each Logic class.

Checklist

  • input_requirements covers all valid input dtypes with OneOf
  • Multi-input ops require matching dtypes with == constraints
  • Optional parameters guarded with If(GetInput("x") != None, ...)
  • output_guarantees specify the output dtype relationship
  • & used to combine multiple requirements (not nested And() calls)
  • Test both valid and invalid dtype combinations

nvidia의 다른 스킬

compileiq-debug
nvidia
무언가 잘못되었을 때 사용: Search()가 멈추거나, 모든 평가가 INVALID_SCORE를 반환하거나, 점수가 개선되지 않거나, 모든 설정이 동일한 숫자를 반환하거나, ptxas 오류 등이 발생할 때
create-github-pr
nvidia
gh CLI를 사용하여 GitHub 풀 리퀘스트를 생성합니다. 사용자가 새 PR을 만들거나, 코드 리뷰를 제출하거나, 풀 리퀘스트를 열고자 할 때 사용합니다. 트리거 키워드 -…
nemoclaw-maintainer-cross-issue-sweep
nvidia
다른 열린 이슈들을 스캔하여 주어진 PR이 함께 수정하거나 실수로 망가뜨릴 수 있는 이슈를 찾습니다. 인접 수정 기회와 모순 위험을 file:line…과 함께 출력합니다.
fhir-basics
nvidia
에이전트에게 FHIR R4 API의 작동 방식, 사용 가능한 리소스, 검색 매개변수를 사용한 쿼리 방법, 모든 응답 형식을 올바르게 파싱하는 방법을 가르칩니다…
compileiq-validate-result
nvidia
검색이 완료된 후, 속도 향상을 청구하거나 ACF를 발송하기 전에 사용합니다. dump_results CSV를 로드하고, 상위 K개 후보(단일 목표)를 추출합니다…
changelog-audit
nvidia
릴리스 전에 Warp CHANGELOG.md를 감사합니다: 누락된 항목 복구, 사용자 영향별 정렬, 항목 언어 다듬기, 줄 바꿈, (릴리스 브랜치 모드) 비교 업데이트…
maintain-dynamic-plugins
nvidia
NeMo Relay 동적 플러그인 로더, 매니페스트, Rust 네이티브 SDK, gRPC 워커 프로토콜, Python 워커 SDK, 문서, 테스트 및 릴리스 워크플로 커버리지를 유지 관리합니다.
dgx-diagnose
nvidia
일반적인 DGX Station GB300 문제 진단 — CUDA 충돌, 잘못된 GPU 타겟팅, vLLM/SGLang 컨테이너 버그, MIG 상태 문제, NVLink/Fabric Manager 오류,…