LiteRT ATS Op Generator Onboarding Skill
This skill guides you through the complete end-to-end workflow for onboarding a
new operator into the LiteRT Accelerator Test Suite (ATS)
(//litert/ats/).
ATS validates hardware accelerator backends (CPU/XNNPACK, GPU, Qualcomm QNN,
Metal, WebGPU, MediaTek, Google Tensor, Intel OpenVINO) by generating
self-contained single-op or composite-op LiteRtModelT graphs with randomized
shapes/parameters, executing them on the target accelerator, and comparing
outputs against a known-good CPU reference implementation.
Reference Guides (Progressive Disclosure)
Read the relevant reference file before writing code:
- references/primitive_op_patterns.md:
Copy-pasteable C++ templates and idioms for Primitive TFLite Ops
(
SingleOp/CoreSingleOp), covering authoring missingReference<Op>kernels, simple ops, shape-inferred ops, static constant tensor inputs (axes, weights, biases), and affine quantization. - references/composite_op_patterns.md:
Copy-pasteable C++ templates and idioms for StableHLO Composite Ops
(
CompositeOp), coveringkStratifiedGrid, Flexbuffer attributes, single- and multi-outputStableHLOCompositedecompositions, and extendingReferenceEvaluator.
End-to-End Onboarding Workflow (The 4 Touchpoints)
Every ATS op onboarding touches ONLY 4 places in
litert/test/generators/ and
litert/ats/ (aside from any missing upstream
litert::tensor or core/model/ops/<op>.h prerequisites in Step 0):
- Generator Header:
test/generators/<op>.h+ header-onlycc_libraryintest/generators/BUILD(never create atest/generators/<op>_test.ccfile orcc_testtarget) - Umbrella Export:
#includeintest/generators/generators.h+ dependency intest/generators/BUILD(:generators) - ATS Registration:
ats/register_<op>.h+ats/register_<op>.cc+cc_libraryinats/BUILD - Bundle & Backend Wiring:
ats/register_{single,composite}_ops.cc+ats/BUILD(including--dont_registerexclusions if a backend lacks support)
Step 0: Classify the Op & Verify Prerequisites
Before creating files, determine whether the target op is a Primitive TFLite Op or a StableHLO Composite Op, and check its upstream building blocks in the live workspace. If the user instead asks "what op should I onboard next?", dynamically compare what is already registered in register_single_ops.cc, register_composite_ops.cc, and test/generators/BUILD against the ops available in core/model/BUILD and tensor/arithmetic.h:
For Primitive TFLite Ops:
- Graph Builder (
litert::tensor): Check tensor/arithmetic.h and arithmetic_tflite.h forlitert::tensor::<Op>(...).- Always prefer the declarative
litert::tensor::Tensor<litert::tensor::TfLiteMixinTag>+SaveTensorGraph({output})API over legacySingleOpModel. - If the op is missing from
litert::tensor, wire it through all 5 places intensor/soSaveTensorGraphcan both serialize and parse the TFLite flatbuffer:- arithmetic_graph.h:
Define
struct <Op>Operation. - arithmetic.h:
Add the
litert::tensor::<Op>(...)builder (if an elementwise op's output dtype differs from its inputs—such asType::kBOOLfor comparison ops—overrideGetInfo(output.GetRaw())->typeinsideElementwiseOp). - arithmetic_tflite.h
&
arithmetic_tflite.cc:
Declare and implement
Build<Op>. - tflite_flatbuffer_conversion.cc:
Register
graph::<Op>OperationinOpConverter. - tflite_flatbuffer_parser.cc:
Add the
tflite::BuiltinOperator_<OP>case soSaveTensorGraphcan parse the serialized flatbuffer back intoLiteRtModelT.
- arithmetic_graph.h:
Define
- Always prefer the declarative
- Reference Kernel & Shape Inference (
litert/core/model/ops/): Check core/model/BUILD (ops_*targets) forlitert::internal::Reference<Op>andlitert::internal::Infer<Op>.- LiteRT Reference Kernel Methodology: LiteRT authors its own
standalone, self-contained C++ reference kernels in
litert/core/model/ops/<op>.h—do not wrap legacytflite::reference_ops(//third_party/tensorflow/lite/kernels/internal:reference_base). - Float-First Design: Compute/math reference kernels operate purely on
floatbuffers (const float*,float*), while generators convert arbitrary input/output types (float,tflite::half, etc.) viaUnpackToFloatandPackFromFloat. Pure data-movement/indexing/comparison ops (Slice,Select,Transpose,Tile,Concatenation) usetemplate <typename T>(ortemplate <typename InT, typename OutT>when input and output element types differ). - If
Reference<Op>is missing: AddReference<Op>(andInfer<Op>if creating a new header) tolitert/core/model/ops/<op>.h, add unit tests inlitert/core/model/ops/<op>_test.cc, and register it inReferenceEvaluator::RegisterStandardOps(). See Section 0 of references/primitive_op_patterns.md for full details.
- LiteRT Reference Kernel Methodology: LiteRT authors its own
standalone, self-contained C++ reference kernels in
For StableHLO Composite Ops:
- Decomposed Primitive Ops in
litert::tensor: Verify that every primitive op used inside yourdecomposelambda exists in tensor/arithmetic.h. - Decomposed Primitive Ops in
ReferenceEvaluator: Composite ops compute reference outputs by running the decomposed subgraph throughReferenceEvaluator::EvaluateCompositeReference.- Inspect
ReferenceEvaluator::RegisterStandardOps()to confirm everykLiteRtOpCodeTfl*emitted by yourdecomposelambda is registered. - If any primitive op is missing from
reference_evaluator.cc, register its handler there and add a test case in reference_evaluator_test.cc.
- Inspect
Step 1: Author the Generator (test/generators/<op>.h & test/generators/BUILD)
Read references/primitive_op_patterns.md
(for primitive ops) or
references/composite_op_patterns.md (for
composite ops) and create
litert/test/generators/<op>.h.
[!WARNING] Avoid Legacy
SingleOpModeland Generator Test Anti-Patterns:
- Do NOT create standalone
<op>_test.ccfiles orcc_testtargets intest/generators/: Existing*_test.ccfiles intest/generators/(sdpa_test.cc,unary_test.cc,binary_no_bcast_test.cc) are legacy. Standalone generator unit tests are redundant because reference math is tested incore/model/ops/<op>_test.cc(orreference_evaluator_test.cc) and the generator itself is verified end-to-end by:register_ops_contract_test,:builtin_ats,:ats, and:ynnpack_ats.- Do NOT edit
FbOpTypesintest/generators/common.h(FbOpTraits/FbOpTraitsNoOptions) when building graphs withlitert::tensor+SaveTensorGraph.FbOpTypesis only used by legacySingleOpModel.- Do NOT write custom
GetTensorType<T>()helpers in your generator. Uselitert::tensor::ApiType<T>::valuedirectly (including fortflite::half, which is specialized intensor/backends/tflite/arithmetic_tflite.h).- Do NOT include
litert_c_types_printing.hin generator headers.
The 7 Non-Negotiable Generator Invariants
-
All Template Parameters Must Be Types:
RegisterCombinationsandExpandProductonly expand C++ types, never non-type template parameters (size_t,bool, enums).- Wrap compile-time constants using the wrappers in
test/generators/common.h:
- Ranks / integers / axes:
SizeC<N>(andSizeListC<1, 2, 3, 4>) - Opcodes:
OpCodeC<kLiteRtOpCodeTfl...>(andOpCodeListC<...>) - Fused activations:
FaC<tflite::ActivationFunctionType_...>(andFaListC<...>) - Booleans:
std::true_type/std::false_type(std::bool_constant<bool>)
- Ranks / integers / axes:
-
TestLogicTraitsInputTypes Must Only List Dynamic Runtime Inputs:using Traits = TestLogicTraits<TypeList<InTypes...>, TypeList<OutTypes...>, Params>;- Only include tensors passed at runtime in
MakeInputs()inInputTypes. Static constant tensors baked into the graph vialitert::tensor::Create(..., data)orOwningCpuBuffer::CopyAs(...)(such as reductionaxes,Slicebegin/sizeconstants,FullyConnectedstatic weights/biases, or static normalization scale weights) are not subgraph runtime inputs—omit them fromInputTypesandMakeInputs(). (ReferenceEvaluator::EvaluateCompositeReferenceautomatically binds constant composite inputs from the graph's buffers.)
-
Provide Both
Create(Rng& rng)andCreate(Params params):- Implement
static Expected<Ptr> Create(Rng& rng)to sample randomized shapes/parameters and delegate tostatic Expected<Ptr> Create(Params params). - Exposing
Create(Params)separates parameter sampling from graph construction and allows deterministic instantiation with explicit shapes.
- Implement
-
Name()Must Return a Static PascalCase Family Name:TestNames::CreateusesLogic::Name()as the<Family>component of the GTest suite name (<Prefix>_<Fixture>_<Family>, e.g.,CoreSingleOp_inference_SliceorCompositeOp_inference_Sdpa).- Return a static string literal for both primitive and composite ops (e.g.,
return "Slice";,return "SelectV2";,return "Sdpa";)—never embed random runtime dimensions inName(). - The individual GTest case name is automatically formatted from the
generated
LiteRtModelTgraph viaNormalizeGraphName(FormatGraph(graph))and verified byregister_ops_contract_test.cc.
-
Preserve Deterministic Dummy Builders in
MakeInputs():- When constraining float ranges in
MakeInputs()(to preventNaN/Infoverflow in FP16 or transcendental ops), always guard withif (!data_builder.IsFloatDummy()):cppRandomTensorDataBuilder builder = data_builder; if (!builder.IsFloatDummy()) { builder.SetFloatRange(-2.0f, 2.0f); } - Without
if (!builder.IsFloatDummy()), callers that setdata_builder.SetFloatDummy()for sequential{0, 1, 2, ...}inputs will have their range overwritten.
- When constraining float ranges in
-
Follow the Float-First
UnpackToFloat/PackFromFloatPattern inReference():- When
Reference<Op>incore/model/ops/operates onfloat*buffers (the standard LiteRT convention for math, reduction, activation, convolution, and matmul ops), unpack inputs (float,tflite::half, etc.) tostd::vector<float>usingUnpackToFloat(in.data), run thefloatreference kernel, and pack back usingPackFromFloat(absl::MakeConstSpan(out_f32), out.data). - When
Reference<Op>is a pure data-movement or comparison op templated directly onT(e.g.,ReferenceSlice<T>,ReferenceSelect<T>,ReferenceTranspose<T>,ReferenceTile<T>,ReferenceConcatenation<T>), passin.data.data()andout.data.data()directly.
- When
-
Choose the Right
GetConformanceSpec()Comparator:Op Category ConformanceComparatorKindRequired Spec Fields Examples Data movement / indexing / comparison kExactspec.comparator_kind = ConformanceComparatorKind::kExact;Slice,SelectV2,Transpose,ExpandDims,SqueezeElementwise float / simple composite kFloatElementwiseDefault ( ConformanceSpec{})Unary,SwiGLU,QkvNormRopeReductions, norms, matmuls, attention kFloatAccumulationAwarespec.accumulation_depth = <reduction_elements>;Mean,Softmax,BatchMatmul,FullyConnected,SdpaQuantized int8 / uint8 ops kQuantizedBucketspec.bucket_tolerance = 1;Quantized FullyConnected
Add the cc_library target for <op> in
test/generators/BUILD.
Step 2: Export in generators.h & test/generators/BUILD
- Add the
#include(in alphabetical order) to generators.h:cpp#include "litert/test/generators/<op>.h" // IWYU pragma: export - Add
":<op>"to thedepsofcc_library(name = "generators", ...)in test/generators/BUILD.
Step 3: Register the Op in ATS (litert/ats/)
- Create
litert/ats/register_<op>.handregister_<op>.cc:- Declare and define both
AtsInferenceTest::Capture&andAtsCompileTest::Capture&overloads ofRegister<Op>(const AtsConf& options, size_t& test_id, size_t iters, ...). - Use
RegisterCombinations<Fixture, <Op>, ...>(iters, test_id, options, cap);. - Add
cc_library(name = "register_<op>", ...)in ats/BUILD.
- Declare and define both
- Wire into the Appropriate Registration Bundle:
- Primitive TFLite Ops ->
register_single_ops.cc:
- Used for all primitive single ops. Linked into all hardware
backend ATS targets (
:ats,:cpu_ats,:gpu_ats,:qualcomm_ats,:metal_macos_ats,:webgpu_macos_ats) and:register_ops_contract_test. - Automatic
"CoreSingleOp"vs."SingleOp"Classification:TestNames::Createautomatically inspects the op'sLiteRtOpCodeagainstIsCoreSingleOp(LiteRtOpCode)in ats/common.h. IfIsCoreSingleOpreturns true, the test suite receives the"CoreSingleOp"prefix; otherwise it receives"SingleOp".
- Used for all primitive single ops. Linked into all hardware
backend ATS targets (
- StableHLO Composite Ops ->
register_composite_ops.cc:
- Required for StableHLO composite ops (
TestNames::Createautomatically assigns"CompositeOp"when the top-level op iskLiteRtOpCodeShloComposite). Linked into all backend ATS targets and:register_ops_contract_test. - Important: Set
/*iters=*/inregister_composite_ops.ccto>= kGridSize(e.g.,16or20) so every entry in yourkStratifiedGridis executed!
- Required for StableHLO composite ops (
- Primitive TFLite Ops ->
register_single_ops.cc:
- Add
":register_<op>"todepsof:register_single_ops(for primitive ops) or:register_composite_ops(for composite ops) in ats/BUILD.
Step 4: Run Mandatory Verification Gates & Configure Backend Exclusions
Always run these verification commands using
/google/bin/releases/arca9-local-blaze-cli/blaze-for-agents:
- Registration Contract Test (instantiates
Create(rng)across all registered combinations and verifies suite prefix, uniqueness, and signature formatting):bash/google/bin/releases/arca9-local-blaze-cli/blaze-for-agents test //litert/ats:register_ops_contract_test - Targeted ATS Execution for the New Op:
bash
/google/bin/releases/arca9-local-blaze-cli/blaze-for-agents run //litert/ats:builtin_ats -- --do_register=".*<OpName>.*" /google/bin/releases/arca9-local-blaze-cli/blaze-for-agents run //litert/ats:ats -- --do_register=".*<OpName>.*" - Full Host CPU (Built-in, XNNPACK & YNNPACK) ATS Regression Checks:
bash
/google/bin/releases/arca9-local-blaze-cli/blaze-for-agents test \ //litert/ats:builtin_ats \ //litert/ats:ats \ //litert/ats:ynnpack_ats- Why
:builtin_atsIs Essential::builtin_ats(and:builtin_cpu_ats) runs the TFLite built-in CPU kernels (--cpu_kernel_mode=builtin, no delegate) directly against your generator'sReference(), validating graph construction and reference outputs end-to-end even when an op is excluded inXNNPACK_DONT_REGISTERon:ats(note thatBUILTIN_DONT_REGISTERexcludes_f16because TFLite built-in CPU kernels do not supportFLOAT16tensors). - Handling Unsupported Ops/Types on CPU Delegates (3 Exclusion Lists):
:atsand:cpu_atsrun against the XNNPACK CPU delegate (backend = "cpu"),:cpu_macos_atshas its own inlinedont_registerlist mirroringXNNPACK_DONT_REGISTER, and:ynnpack_ats/:ynnpack_cpu_atsuseYNNPACK_DONT_REGISTERin ats/BUILD. Neither delegate supports every primitive op, data type, or composite op (for example,OneHot,SelectV2,tfl.floor_div,Swiglu,QkvNormRope, orSdpaTransposed).- If
:atsor:ynnpack_atsfails because XNNPACK or YNNPACK does not support your new op or specific template combinations, add a narrow regex with an explanatory comment to all applicable CPU exclusion lists in ats/BUILD:XNNPACK_DONT_REGISTER:cpu_macos_ats's inlinedont_registerlist (keep in sync withXNNPACK_DONT_REGISTER)YNNPACK_DONT_REGISTER
- Re-run
:builtin_ats,:ats, and:ynnpack_atsto confirm all three are green, and runbuild_cleaneronlitert/test/generators/BUILDandlitert/ats/BUILDif needed.
- Why


