You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We want to provide an easy mechanism to utilize FP8 in inference, and see both decreased memory usage and performance gains on hardware that supports native FP8 computation. We would like the API to require minimal model rewrites. We also want it to be configurable in such a way as to provide multiple levels of scaling granularity with their own accuracy/performance trade-offs. The solution should be composable with other inference components in the PyTorch ecosystem:
Export
AOTI
Dynamic Shapes
This solution is targeting server-side GPU inference. It is not currently focused on supporting edge or CPU inference.
Background
Float8 inference can be used to reduce memory usage and improve computational efficiency. By using FP8 instead of higher precision formats, we can achieve significant speedups and memory savings with minimal loss in accuracy. The memory saving is unique to float8 inference as opposed to float8 training. For inference, the weights are static and thus do not need the higher precision during weight updates.
Proposal
Float8InferenceLinear Module
We propose a new Float8InferenceLinear module that extends nn.Linear with Float8 quantization capabilities:
This module handles the quantization of weights and activations based on the provided configuration. This module was landed in this PR: #287. It is designed to replace a pre-trained nn.Linear module in an existing model and statically convert the weight to FP8. By default, we do this in E4M3 format.
It provides configuration options via the QuantConfig class to encapsulate various quantization settings:
classActivationCasting(Enum):
"""Types of quantization to perform on the activations WEIGHT_ONLY: Only quantize the weight, no activation casting, weight will be dequantized in the forward pass STATIC: Activation is quantized during model initialization with a static scale DYNAMIC: Activation is quantized during forward pass with a dynamic scale calculated from the input activation """# TODO: A better name would be NONE, we should unify this with torchaoWEIGHT_ONLY=auto()
DYNAMIC=auto()
STATIC=auto()
The main configuration options are captured in the ActivationCasting enum:
dynamic casting: This setting will cast the activation to nn.Linear to a scaled fp8 type during the forward pass and run _scaled_mm.
static quantization: This will use a pre-calculated activation scale for casting the activation to E4M3. Currently, we don't specify how this scale is to be calculated.
weight-only: This config stores weights in scaled fp8 but during inference we dequantize the float8 weight and run the matmul in the activation's precision.
This function allows users to easily convert their models to use Float8 inference.
An example of how this can be used on a Hugging Face model can be found in this PR in TorchAO
Proposed Extensions
Scaling Granularity
Currently, we only support TensorWise scaling. Concretely, this is done by calculating the max(abs(Tensor)) and utilizing this value to compute the Float8Tensor scale. However, due to outlier values in activations, this can have large quantization error. As well, calculating a global reduction across the entire activation tensor can be relatively slow.
Therefore, we want to add the option to specify different types of scaling granularities.
The scaling_granularity parameter determines how scales are computed:
TensorWise: A single scale is computed for the entire tensor.
AxisWise: Scales are computed along a specified axis of the tensor.
We recently added Axiswise scaling support to _scaled_mm in this PyTorch PR: #128989. As well, I have a worked PR stack showing how Axiswise scaling can be implemented in Float8Experimental: meta-pytorch/float8_experimental#305
We would like to continue generalizing the scaling granularity to:
GroupWise: Similar to AxisWise but instead of one scale per axis, we have multiple
BlockWise: All other forms can be seen as special cases of this. Scale per 2D tile of activation and weight.
Design Details
Tensor Subclass Usage
The implementation utilizes Float8Tensors to encapsulate the scaling as well as dispatch to _scaled_mm instead of torch.mm. This is not the only way this could be implemented. Since we do not have the autograd constraint that backpropagating grads must match the dtype of the tensor in the forward, we are free to desugar the Float8Tensor into its constituents, store them on the module, and use them in the forward. However, using the tensor subclass, allows us to re-use similar components between training and inference, but it does have downsides:
For people less familiar with Tensor Subclass, this indirection can be confusing.
This makes supporting torch.Export more challenging.
Performance
Compile
As with the rest of this project, we heavily rely on the compile stack to generate efficient and fused casting code. We do actually see some performance gains on heavily compute-bound models, but in general, we require torch.compile for competitive performance.
Export
Currently, it is not possible to run torch.export + AOTI with the publicly available export APIs. However, this PR: meta-pytorch/float8_experimental#295 demonstrates that it is possible. There are plans this half for the export team to make export of nn.modules with subclasses as weights available in the public API.
Limitations and Future Work
Extend ScalingGranularity
Limited Dtype Support: Currently, AxisWise scaling is only supported for bfloat16.
Kernel Support: _scaled_mm only supports TensorWise and AxisWise scaling; work is needed to extend to other granularities.
Existing Kernel Improvement: In early experiments, the AxisWise kernel is shown to not be as performant as the TensorWise kernel. Investigation is needed here.
Activation Folding: The current implementation doesn't support folding of leading dimensions for activations, which may be necessary for certain model architectures. Due to needing to calculate scales prior to construction of the Float8Tensor, we do not get to utilize the decomposition for Linear to do the unfolding for us.
Composition with other dtypes/techniques
There are various low-bit dtypes that users may want to use. TorchAO has a number of these - AffineQuantized, NF4Tensor, int4_weight_only, etc. It is possible that users will want to compose different types within the same model. Work is needed here to ensure that the top-level UX is expressive enough to handle these cases.
Standardize on TorchAO APIs
StaticCalibration Flow: This RFC does not aim to provide a static calibration flow. We would like to share this API with TorchAO. An early prototype of which can be found here: Add static quantization as an example for calibration flow #487, and we should ensure we are composable.
TorchAO provides an autoquant API. This API relies on the entirety of the inference logic to be encapsulated in the subclass. That is not the case today, and work is needed to make sure that we can compose well here.
Non-H100 GPU Support
_scaled_mm's TensorWise support is enabled on sm89, and MI300x + GPUs. However, the AxisWise kernel is based on Cutlass and is not currently supported on any GPU besides H100.
Dynamic Shapes
Work is needed to validate that dynamic shapes is working as expected.
Other Module Support
-While Linear weights take up the majority of model size and compute, other operations can still be amenable to the compute gains from FP8
For transformer models we will likely need to support a fused FP8 SDPA variant. With the recent addition of the CuDNN SDPA to PyTorch core and the upgrade to CuDNN 9.1 we could utilize this library for this. However, work is needed to explore the various options.
The KVCache can contribute a significant proportion of the total memory usage during autoregressive decoding. We can investigate utilizing FP8 for storing quantized kv tokens.
Examples
# Example usage of the proposed APImodel=MyLargeModel()
quant_config=QuantConfig(ActivationCasting.DYNAMIC)
quantized_model=quantize_to_float8(
model,
quant_config,
scaling_granularity=ScalingGranularity.AxisWise
)
quantized_model=torch.compile(quantized_model)
# Use the quantized model for inferenceinput_tensor=torch.randn(1, 1024, 1024, dtype=torch.bfloat16, device="cuda")
output=quantized_model(input_tensor)
Open Questions
Should we provide more granular control over which layers are quantized? This is possible today using FQNs but not sure if TorchAO has ideas on top-level UX.
How can we best handle models with custom or non-standard linear layers?
What additional tools or utilities might be needed to help users debug and optimize their quantized models?
Quantization Error Reducing Techniques: Techniques like HQQ are utilized to reduce quantization error. It is unlikely that the existing _scaled_mm kernel can support this use case. Is that a problem?
Conclusion
This RFC proposes significant enhancements to Float8 inference in PyTorch, aiming to provide a more flexible, efficient, and user-friendly framework for quantization. By supporting various scaling granularities and quantization strategies, we can cater to a wide range of use cases and potentially unlock substantial performance improvements for many models.
RFC: Float8 Inference
Objective
We want to provide an easy mechanism to utilize FP8 in inference, and see both decreased memory usage and performance gains on hardware that supports native FP8 computation. We would like the API to require minimal model rewrites. We also want it to be configurable in such a way as to provide multiple levels of scaling granularity with their own accuracy/performance trade-offs. The solution should be composable with other inference components in the PyTorch ecosystem:
This solution is targeting server-side GPU inference. It is not currently focused on supporting edge or CPU inference.
Background
Float8 inference can be used to reduce memory usage and improve computational efficiency. By using FP8 instead of higher precision formats, we can achieve significant speedups and memory savings with minimal loss in accuracy. The memory saving is unique to float8 inference as opposed to float8 training. For inference, the weights are static and thus do not need the higher precision during weight updates.
Proposal
Float8InferenceLinear Module
We propose a new
Float8InferenceLinearmodule that extendsnn.Linearwith Float8 quantization capabilities:This module handles the quantization of weights and activations based on the provided configuration. This module was landed in this PR: #287. It is designed to replace a pre-trained nn.Linear module in an existing model and statically convert the weight to FP8. By default, we do this in E4M3 format.
It provides configuration options via the
QuantConfigclass to encapsulate various quantization settings:The main configuration options are captured in the
ActivationCastingenum:_scaled_mm.Top-level API
We propose a top-level API for quantizing models:
This function allows users to easily convert their models to use Float8 inference.
An example of how this can be used on a Hugging Face model can be found in this PR in TorchAO
Proposed Extensions
Scaling Granularity
Currently, we only support TensorWise scaling. Concretely, this is done by calculating the
max(abs(Tensor))and utilizing this value to compute the Float8Tensor scale. However, due to outlier values in activations, this can have large quantization error. As well, calculating a global reduction across the entire activation tensor can be relatively slow.Therefore, we want to add the option to specify different types of scaling granularities.
The
scaling_granularityparameter determines how scales are computed:TensorWise: A single scale is computed for the entire tensor.AxisWise: Scales are computed along a specified axis of the tensor.We recently added Axiswise scaling support to
_scaled_mmin this PyTorch PR: #128989. As well, I have a worked PR stack showing how Axiswise scaling can be implemented in Float8Experimental: meta-pytorch/float8_experimental#305We would like to continue generalizing the scaling granularity to:
GroupWise: Similar to AxisWise but instead of one scale per axis, we have multipleBlockWise: All other forms can be seen as special cases of this. Scale per 2D tile of activation and weight.Design Details
Tensor Subclass Usage
The implementation utilizes Float8Tensors to encapsulate the scaling as well as dispatch to
_scaled_mminstead oftorch.mm. This is not the only way this could be implemented. Since we do not have the autograd constraint that backpropagating grads must match the dtype of the tensor in the forward, we are free to desugar the Float8Tensor into its constituents, store them on the module, and use them in the forward. However, using the tensor subclass, allows us to re-use similar components between training and inference, but it does have downsides:Performance
Compile
As with the rest of this project, we heavily rely on the compile stack to generate efficient and fused casting code. We do actually see some performance gains on heavily compute-bound models, but in general, we require torch.compile for competitive performance.
Export
Currently, it is not possible to run torch.export + AOTI with the publicly available export APIs. However, this PR: meta-pytorch/float8_experimental#295 demonstrates that it is possible. There are plans this half for the export team to make export of nn.modules with subclasses as weights available in the public API.
Limitations and Future Work
Extend ScalingGranularity
bfloat16._scaled_mmonly supports TensorWise and AxisWise scaling; work is needed to extend to other granularities.Composition with other dtypes/techniques
AffineQuantized,NF4Tensor,int4_weight_only, etc. It is possible that users will want to compose different types within the same model. Work is needed here to ensure that the top-level UX is expressive enough to handle these cases.Standardize on TorchAO APIs
Non-H100 GPU Support
_scaled_mm's TensorWise support is enabled on sm89, and MI300x + GPUs. However, the AxisWise kernel is based on Cutlass and is not currently supported on any GPU besides H100.Dynamic Shapes
Other Module Support
-While Linear weights take up the majority of model size and compute, other operations can still be amenable to the compute gains from FP8
Examples
Open Questions
_scaled_mmkernel can support this use case. Is that a problem?Conclusion
This RFC proposes significant enhancements to Float8 inference in PyTorch, aiming to provide a more flexible, efficient, and user-friendly framework for quantization. By supporting various scaling granularities and quantization strategies, we can cater to a wide range of use cases and potentially unlock substantial performance improvements for many models.
Additional Details
Utilizing this script: https://gist.github.com/drisspg/d7ae2134fbb6ca369c4817853c3352fa