BladeDISC Documentation
repository·main·Indexed 21 days ago
https://github.com/alibaba/bladediscAn end-to-end dynamic shape compiler for machine learning workloads that provides performance optimizations for TensorFlow and PyTorch across various CPU and GPU backends. It includes torch_blade for PyTorch acceleration via TorchScript compilation and FoldAcc for optimizing AlphaFold models using Automatic Mixed Precision (AMP) and Tensor Parallelism.
What's inside BladeDISC
- TorchBlade is an end-to-end performant compiler designed for a subset of the Python language used in deep learning. Its primary focus is the optimization and compilation of PyTorch models specifically for inference workloads.
What is BladeDISC?
mainBladeDISC is an end-to-end DynamIc Shape Compiler designed for machine learning workloads. It provides transparent performance optimization for TensorFlow and PyTorch workloads on GPGPU and CPU backends.
Key characteristics include:
- Native Dynamic Shape Support: Optimized for both static and dynamic shape scenarios.
- MLIR-based: Built on the MLIR framework and closely related to the
mlir-hloproject. - Flexible Deployment: Supports both Plugin Mode (running as a plugin within the original framework runtime) and Standalone Mode (AOT compilation into a self-contained binary).
Overview of DISC Custom call plugin
mainThedisc-pdlltool is a DISC Custom call plugin built on top of MLIR PDLL (Pattern Description Language). It is used within thetao_compilerecosystem to handle custom call patterns.Benchmark TorchBlade's TensorRT Optimization
mainTorchBlade supports optimization via multiple backends. TensorRT is an accelerator integrated via ONNX. You can benchmark TensorRT optimization using the provided scripts for Detectron2 and torch-tensorrt.Performance benefits of TorchBlade for Detectron2
mainUsing TorchBlade with a TensorRT backend can significantly improve Detectron2 inference performance. Benchmarks show improvements of up to 2.7x compared to standard Torch execution. For example, inCascadeRCNN(fp16), median FPS increases from ~19.6 to ~36.5.Walkthrough of the BladeDISC Pass Pipeline
mainThe BladeDISC compilation process follows a multi-stage pass pipeline that transforms high-level TensorFlow/PyTorch IR into optimized machine code for both CPU and GPU. The pipeline is divided into several major phases:
- TF-to-HLO Passes: Converts TensorFlow dialect to HLO (High-Level Optimizer) dialect. This phase includes standard MLIR-HLO pipelines and BladeDISC-specific passes like
DiscLowerTfPass(for custom ops likeRandomUniformandTopK) andReviseArgumentsForStaticRankPass. - HLO Graph Optimization & Placement: Optimizes the HLO graph and decides where operations should execute. Key components include the
ShapeSimplifierpass (for shape propagation and constraint insertion) andPlacement Passes(which mark shape-calculation ops to be executed on the CPU). - Bufferize Passes: Transitions the IR from the 'tensor world' to the 'buffer world' by explicitly emitting allocation and deallocation logic. This includes converting
mhlotolmhlo(the bufferized representation) and assigning memory spaces (CPU vs. GPU). - LHLO Graph Optimization Passes: Performs optimizations on the bufferized representation, most notably the Fusion Pass (using 'base' or 'stitch' strategies) and the Speculation Pass (generating multiple kernel versions for different runtime conditions like vectorization or implicit broadcasts).
- Runtime & Library Call Related Passes: Integrates the Runtime Abstraction Layer (RAL). It injects the RAL context and rewrites custom call ops into
disc_ral.dispatchops to ensure a stable ABI and manage stateful resources. - CodeGen Passes: Lowers
lmhlo.fusionops into nested loops. This phase is backend-aware (CPU vs. GPU) and uses backbone passes likeDiscLhloLegalizeRootsToParallelLoopsPassandInputInlineFusionPassto generate schedules. - Loops to GPU / GPU Module to CUBIN: For GPU backends, this phase tiles loops, maps them to GPU blocks/threads, and lowers the GPU dialect to vendor-specific dialects (NVVM for CUDA or ROCm for AMD) before compiling to a binary blob.
- Host Side Passes: Generates the scheduling logic (kernel launching, data movement, synchronization) and lowers the final IR to the LLVM dialect for binary generation.
- TF-to-HLO Passes: Converts TensorFlow dialect to HLO (High-Level Optimizer) dialect. This phase includes standard MLIR-HLO pipelines and BladeDISC-specific passes like
What is Speculation in BladeDISC?
mainBecause shapes are unknown at compile time, standard optimizations like data vectorization or schedule selection are difficult. BladeDISC uses a process called speculation: it generates multiple versions of kernels at compile time and generates host-side code to select and launch the most appropriate kernel version at runtime based on the actual shapes.Use the Quantizer class for PyTorch quantization
mainThe primary interface for the toolkit is the
Quantizerclass. You instantiate aQuantizerwith configuration (such as target backend type or excluded module types) and use it to generate different types of proxy models depending on your stage in the workflow:- Calibration Proxy: Created via
Quantizer.calib(model). Used to calibrate parameters by running forward passes with typical data. - QAT Proxy: Created via
Quantizer.qat(model). Used for Quantization-Aware Training. - Quantized Model Proxy: Created via
Quantizer.quantize(model). Represents the final quantized model ready for inference or export.
from torch_quant import Quantizer model = MyModel() # torch.nn.Module quantizer = Quantizer() # For calibration calib_model = quantizer.calib(model) # For QAT qat_model = quantizer.qat(model) # For final quantized model quant_model = quantizer.quantize(model)- Calibration Proxy: Created via
How the compiler interacts with RAL via Context Injection
mainTo simplify the compiler's core optimization logic, BladeDISC uses Context Injection. All RAL APIs are required to take a context object as their first argument.
During compilation, a transformation pass rewrites the entry function and all related functions to ensure the context is passed through. In the MLIR intermediate representation, this is modeled using the
disc_raldialect and thedisc_ral.RalExecutionContextTypetype, which eventually lowers to a pointer in LLVM IR.How inputs and outputs are bound in RAL
mainTo maintain a stable ABI and hide the implementation details of memory structures (like
MemRef), the compiler rewrites the entry function's inputs and outputs. Instead of receiving raw buffers, the function receives a context and usesrecv_inputandsend_outputAPI calls to interact with the RAL.This design allows for partial execution: the compiler can place
recv_inputcalls such that the binary starts executing as soon as specific inputs are ready, orsend_outputcalls to stream results back before all computations are finished.// Original IR func @main(%arg0 : memref<?x?xf32>, %arg1 : memref<?x?xf32>) -> memref<?x?xf32> { %ret = alloc(...) use(%arg0, %arg1, %ret, ...) return %ret : memref<?x?xf32> } // After RAL conversion func @main(!disc_ral.context %ctx) { %arg0 = disc_ral.recv_input(%ctx, 0) // receive the first input %arg1 = disc_ral.recv_input(%ctx, 1) // receive the second input %ret = alloc(...) use(%arg0, %arg1, %ret, ...) disc_ral.send_output(%ctx, 0, %ret) // send the first output }How TorchBlade handles Lists and Dicts
mainTorchBlade's support for Python data structures like
ListandDictis limited to cases where elements can be analyzed statically at conversion time:- Supported:
List[Scalar]andList[Tensor]where elements are known statically. In these cases, TorchBlade imitates the list operations during conversion so theListstructure itself does not need to be preserved in the IR. - Unsupported: If elements cannot be analyzed statically, or if using
Dict, the operations will fallback to the PyTorch runtime.
- Supported:
Understand the Shape Optimization Pass workflow
mainThe shape optimization pass in BladeDISC is a tensor-level, reenterable pass designed to improve shape information within the IR. It operates in two primary stages:
- Stage One: Explicit Materialization: Materializes shape computation IR on the tensor level. This includes (partial) shape inference (e.g., calculating the output shape of a
concatoperation) and enabling optimization opportunities for shape computation IR. - Stage Two: Analysis and Optimization: An iterative process that performs canonicalization, loads existing shape constraint IR, conducts global shape analysis (finding more constraints and injecting constraints implied by
mhloop definitions), performs global shape optimization (using the same SSA value for symbolic equal dimensions), and finally saves the updated information back into the IR.
- Stage One: Explicit Materialization: Materializes shape computation IR on the tensor level. This includes (partial) shape inference (e.g., calculating the output shape of a