CogVideoX-2B ONNX INT4/INT8 CPU
A quantized, CPU-oriented ONNX implementation of CogVideoX-2B for local text-to-video generation.
This project converts the CogVideoX-2B text-to-video pipeline into modular ONNX models, applying INT4 and INT8 quantization to reduce model storage requirements and make CPU-based inference experiments more accessible.
The implementation targets local inference environments, including Apple Silicon systems, without requiring a dedicated NVIDIA GPU.
Highlights
- CogVideoX-2B text-to-video architecture.
- ONNX Runtime inference.
- INT4 RTN transformer quantization.
- INT4 T5 text encoder quantization.
- INT8 VAE decoder quantization.
- INT4 block size 32.
- RTN accuracy level 4.
- CPUExecutionProvider support.
- Modular model components.
- External ONNX tensor data support.
- Configurable inference steps, seed, resolution and FPS.
- DDIM scheduler configuration.
- Classifier-free guidance support in the generation implementation.
- FP32 versus INT4 numerical validation.
- Designed for local and resource-constrained inference experiments.
Model Information
| Property | Value |
|---|---|
| Model | CogVideoX-2B |
| Model type | Text-to-video |
| Architecture | Diffusion Transformer |
| Base model | THUDM/CogVideoX-2b |
| Text encoder | T5 |
| Transformer | CogVideoXTransformer3DModel |
| VAE | AutoencoderKLCogVideoX |
| Model format | ONNX |
| Inference engine | ONNX Runtime |
| Execution provider | CPUExecutionProvider |
| Transformer precision | INT4 |
| Text encoder precision | INT4 |
| VAE precision | INT8 |
| Quantization method | RTN |
| Transformer block size | 32 |
| Quantization accuracy level | 4 |
| Scheduler | CogVideoXDDIMScheduler |
| Video frames | 49-frame configuration |
| Default frame rate | 8 FPS |
Model Architecture
The pipeline consists of three independently executable ONNX components.
1. Text encoder
The T5 text encoder converts the input prompt into text embeddings used to condition the video-generation transformer.
| Property | Configuration |
|---|---|
| Model | T5EncoderModel |
| Tokenizer | T5Tokenizer |
| Precision | INT4 |
| Sequence length | 226 |
| Embedding dimension | 4096 |
| Input | Token IDs and attention mask |
| Output | Text embeddings |
2. Video transformer
The transformer is responsible for iterative video latent denoising.
| Property | Configuration |
|---|---|
| Architecture | CogVideoXTransformer3DModel |
| Precision | INT4 |
| Quantization | RTN |
| Block size | 32 |
| Accuracy level | 4 |
| Latent channels | 16 |
| Input | Video latents, text embeddings and timestep |
| Output | Predicted noise / velocity |
3. VAE decoder
The VAE converts the final denoised latent representation into video frames.
| Property | Configuration |
|---|---|
| Architecture | AutoencoderKLCogVideoX |
| Precision | INT8 |
| Input channels | 16 |
| Output channels | 3 |
| Temporal compression | 4 |
| Spatial compression | 8 |
| Latent scaling factor | 1.15258426 |
The transformer uses video latents in [batch, frames, channels, height, width] order. The VAE decoder uses [batch, channels, frames, height, width] order.
Quantization Configuration
Transformer INT4
The transformer uses RTN quantization with:
- Weight precision: INT4.
- Block size: 32.
- Accuracy level: 4.
- ONNX Runtime MatMulNBits operators.
- External tensor data for large model weights.
The objective is to reduce transformer storage requirements while retaining numerical similarity to the original FP32 graph.
Text encoder INT4
The T5 encoder is quantized independently to reduce the storage footprint of the prompt-conditioning component.
VAE INT8
The VAE decoder uses INT8 quantization to reduce its model storage requirements.
VAE quality should be evaluated independently because small numerical differences in decoded pixels can affect visual quality.
Repository Structure
video-ai-cogvideox-2b-onnx /
│
├── text_encoder/
│ ├── model_int4.onnx
│ └── model_int4.onnx.data
│
├── transformer/
│ ├── model_dynamic_int4.onnx
│ └── model_dynamic_int4.onnx.data
│
├── vae_decoder/
│ ├── model_int8.onnx
│ └── model_int8.onnx.data
│
├── tokenizer/
│
├── scheduler/
│ └── scheduler_config.json
│
├── model_index.json
├── config.json
├── manifest.json
└── README.md
External ONNX tensor data files must be distributed alongside their corresponding ONNX graph files.
Inference Pipeline
The generation process follows this sequence:
- Tokenize the input prompt.
- Generate text embeddings using the T5 ONNX encoder.
- Initialize random video latents.
- Create the scheduler timesteps.
- Execute iterative transformer denoising.
- Apply classifier-free guidance when enabled.
- Pass final latents into the VAE decoder.
- Convert decoded frames into RGB video.
- Encode the output using FFmpeg.
Scheduler
The pipeline uses the CogVideoX DDIM scheduler configuration.
| Parameter | Value |
|---|---|
| Scheduler | CogVideoXDDIMScheduler |
| Beta schedule | scaled_linear |
| Beta start | 0.00085 |
| Beta end | 0.012 |
| Training timesteps | 1000 |
| Prediction type | v_prediction |
| Zero terminal SNR | Enabled |
| SNR shift scale | 3.0 |
| Timestep spacing | trailing |
| Clip sample | Disabled |
| Sampling eta | 0 |
The scheduler implementation should be validated against the corresponding Diffusers reference version before claiming exact numerical parity.
Hardware and Software Environment
Tested environment
| Component | Configuration |
|---|---|
| Device | Apple Silicon MacBook Air |
| System memory | 16 GB |
| Execution | CPU |
| Python | 3.12.15 |
| ONNX Runtime | 1.32.0 |
| ONNX | 1.23.2 |
| PyTorch | 2.15.0 |
| Transformers | 5.23.0 |
| CPU provider | CPUExecutionProvider |
These are the recorded development environment versions. Compatibility with other systems and runtime versions should be tested separately.
Performance Benchmarks
This section distinguishes measured results from future optimization targets.
1. Initial end-to-end inference benchmark
Recorded using the initial 128 × 128 generation configuration.
| Benchmark | Result |
|---|---|
| Resolution | 128 × 128 |
| Frames | 49 |
| FPS | 8 |
| Duration | 6.125 seconds |
| Denoising steps | 10 |
| Guidance scale | 1.0 |
| Seed | 42 |
| Peak process RSS | Approximately 3.78 GB |
| Output size | Approximately 0.12 MB |
| Total generation time | Approximately 154.59 seconds |
2. Pipeline stage timings
| Pipeline stage | Time |
|---|---|
| Text encoder loading | 12.42 s |
| Text encoding | 4.28 s |
| Transformer loading | 7.62 s |
| Transformer denoising | Approximately 85.5 s |
| VAE loading | 2.89 s |
| VAE decoding | 35.16 s |
| Total | Approximately 154.59 s |
The measured transformer denoising time corresponds to approximately 8.55 seconds per step for the recorded 10-step run.
The timing figures are rounded and should be treated as an initial baseline rather than a statistically controlled benchmark.
3. Transformer FP32 versus INT4 accuracy
The transformer was evaluated using identical deterministic random inputs.
| Metric | Result |
|---|---|
| Mean absolute error | 0.04265974 |
| Root mean squared error | 0.05332734 |
| Maximum absolute error | 0.19219160 |
| Cosine similarity | 0.99761802 |
FP32 output statistics
| Metric | Value |
|---|---|
| Mean | -0.04781635 |
| Standard deviation | 0.7217795 |
| Minimum | -1.3008336 |
| Maximum | 1.323802 |
INT4 output statistics
| Metric | Value |
|---|---|
| Mean | -0.0462040 |
| Standard deviation | 0.7390063 |
| Minimum | -1.3934109 |
| Maximum | 1.425022 |
Interpretation: The high cosine similarity indicates strong directional agreement between the FP32 and INT4 outputs for this test input. It does not prove equivalent generated video quality or guarantee similar behavior over the full denoising trajectory.
4. VAE numerical validation
An earlier FP32 ONNX versus PyTorch comparison produced:
| Metric | Result |
|---|---|
| Output shape | 1 × 3 × 49 × 32 × 32 |
| MAE | 0.00000016677 |
| RMSE | 0.00000024185 |
| Maximum absolute error | 0.0000023246 |
This comparison validates the FP32 ONNX decoder against its PyTorch reference for the tested input. It is not an INT8-versus-FP32 quality result.
5. VAE INT8 calibration measurements
Previously recorded synthetic-input calibration results:
| Latent input size | MAE | RMSE | Maximum error |
|---|---|---|---|
| 4 × 4 | 0.00564 | 0.01065 | 0.2714 |
| 8 × 8 | 0.00498 | 0.00650 | 0.1624 |
| 16 × 16 | 0.00627 | 0.03179 | 7.825 |
The larger maximum error at 16 × 16 suggests that calibration outliers require investigation. These measurements should not be interpreted as a final perceptual-quality evaluation.
6. Model storage
| Component | Recorded information |
|---|---|
| Complete ONNX package | Approximately 4.97 GB |
| Transformer external data | Approximately 2.113 GB |
| Transformer graph | INT4 |
| Text encoder | INT4 |
| VAE decoder | INT8 |
The complete package includes model graphs, weights, tokenizer, scheduler and configuration files.
Performance Analysis
Current bottlenecks
The initial benchmark indicates that the major runtime costs are:
- Transformer denoising.
- VAE decoding.
- Model loading and initialization.
- Text encoding.
The transformer is the primary target for inference optimization, while VAE decoding is a substantial secondary target.
Optimization priority 1: Transformer inference
The transformer contains a large number of quantized matrix multiplication operators.
Optimization work should focus on:
- Profiling MatMulNBits execution.
- Identifying expensive operator groups.
- Measuring quantized kernel throughput.
- Comparing intra-op thread configurations.
- Testing sequential versus parallel operator execution.
- Evaluating ONNX Runtime graph optimization levels.
- Measuring memory bandwidth utilization.
- Reducing temporary tensor allocations.
- Reusing input/output buffers where supported.
A key objective is to distinguish whether inference is CPU-compute-bound, memory-bandwidth-bound, or limited by quantized operator implementation.
Optimization priority 2: CPU thread tuning
Benchmark multiple thread configurations rather than assuming more threads are always faster.
Suggested configurations:
| Intra-op threads | Test objective |
|---|---|
| 1 | Single-thread baseline |
| 2 | Low-concurrency inference |
| 4 | Existing benchmark configuration |
| 6 | Increased parallelism |
| 8 | Higher concurrency |
| 10 | Oversubscription investigation |
Record total generation time, transformer time per step, CPU utilization and peak memory for each configuration.
Optimization priority 3: ONNX Runtime session configuration
Evaluate:
- ORT_ENABLE_BASIC.
- ORT_ENABLE_EXTENDED.
- ORT_ENABLE_ALL.
- Intra-op execution mode.
- Inter-op execution mode.
- Execution spinning.
- Thread affinity.
- Memory arena configuration.
- Sequential versus parallel graph execution.
The best configuration must be established experimentally. Operator fusion or graph optimization may not improve every quantized graph.
Optimization priority 4: Classifier-free guidance
Classifier-free guidance requires conditional and unconditional transformer predictions.
For memory-constrained systems, sequential execution can avoid creating a larger combined transformer batch.
Benchmark:
- Guidance disabled.
- Guidance enabled.
- Sequential conditional/unconditional execution.
- Batched conditional/unconditional execution where memory permits.
Measure both execution time and output quality. Guidance is a quality-versus-compute decision, not a free optimization.
Optimization priority 5: VAE decoding
Investigate:
- Intermediate tensor allocation.
- Temporal decoding memory usage.
- Spatial tiling where supported.
- Frame processing strategies where compatible with the VAE architecture.
- INT8 calibration improvements.
- FP32 versus INT8 perceptual quality.
- Buffer reuse.
Any tiled or frame-wise decoding approach must preserve temporal consistency and validate against the original VAE output.
Optimization priority 6: Memory and data movement
Investigate:
- Avoiding unnecessary tensor copies.
- Reducing PyTorch/NumPy conversion overhead.
- Reusing preallocated buffers.
- Avoiding duplicated model sessions.
- Releasing unused intermediate tensors.
- Measuring resident memory and peak memory separately.
- Measuring model load time independently from inference time.
Optimization priority 7: Video encoding
Investigate:
- FFmpeg streaming input.
- Encoding preset selection.
- CRF configuration.
- H.264 bitrate and output size.
- Hardware-accelerated encoding where supported.
Video encoding should be benchmarked separately from neural inference so that encoding performance does not distort model measurements.
Benchmarking Protocol
A reliable performance report should use the following protocol:
- Record hardware and operating system details.
- Record runtime and library versions.
- Load model sessions.
- Execute warm-up iterations.
- Measure repeated inference runs.
- Separate model loading from inference.
- Measure every pipeline stage.
- Record per-step transformer latency.
- Record peak process RSS.
- Record CPU utilization.
- Record output video dimensions and size.
- Validate output frame count and decode integrity.
- Repeat with fixed prompts and seeds.
- Compare numerical output against the reference implementation.
Report median, mean, minimum, maximum and standard deviation rather than relying on one execution.
Recommended Benchmark Matrix
The following is the proposed benchmark suite. These are test configurations, not completed measurements.
Resolution benchmark
| Resolution | Purpose |
|---|---|
| 128 × 128 | Existing smoke-test baseline |
| 160 × 240 | Low-resolution quality test |
| 240 × 320 | Intermediate workload |
| 320 × 480 | Higher-resolution workload |
| 480 × 720 | Original model resolution reference |
The original CogVideoX-2B model is associated with a 480 × 720 video configuration. Arbitrary dynamic ONNX dimensions do not guarantee that every resolution will produce equivalent quality.
Denoising-step benchmark
| Steps | Objective |
|---|---|
| 5 | Aggressive speed experiment |
| 10 | Existing baseline |
| 15 | Intermediate quality/speed test |
| 20 | Higher-quality experiment |
| 30 | Extended denoising experiment |
| 50 | Reference-style inference configuration |
Reduced-step generation must be evaluated for visual quality, not just runtime.
Frame-count benchmark
| Frames | Objective |
|---|---|
| 13 | Short clip |
| 25 | Intermediate clip |
| 49 | Existing configuration |
| 65 | Extended temporal workload |
Validate temporal dimensions and model constraints before treating these as supported configurations.
Quantization benchmark
Compare:
- FP32 reference.
- INT8 transformer.
- INT4 transformer, block size 32.
- Alternative INT4 block sizes where supported.
- INT4 T5 encoder versus reference.
- INT8 VAE versus FP32 reference.
Measure:
- MAE.
- RMSE.
- Maximum absolute error.
- Cosine similarity.
- Model file size.
- Peak memory.
- Inference latency.
- Video perceptual quality.
- Temporal consistency.
Performance Metrics
The following metrics should be reported for every benchmark.
| Metric | Description |
|---|---|
| Model load time | Time to initialize ONNX sessions |
| Prompt encoding time | T5 inference latency |
| Transformer step latency | Average denoising step time |
| Transformer total time | Total denoising duration |
| VAE decode time | Video latent decoding latency |
| Total generation time | Complete end-to-end latency |
| Peak RSS | Maximum resident memory |
| CPU utilization | CPU workload during inference |
| Model storage | Disk footprint |
| Output size | Encoded MP4 size |
| Frames per second | Generated frames divided by total generation time |
| Real-time factor | Generation time divided by video duration |
| Quantization error | Difference against reference output |
Derived performance formulas
Generation throughput
Frames per second:
generated_frames / total_generation_seconds
Real-time factor
generation_seconds / output_video_duration_seconds
Speedup
FP32_generation_time / quantized_generation_time
Storage reduction
(FP32_size - quantized_size) / FP32_size * 100
Memory reduction
(FP32_peak_memory - quantized_peak_memory) / FP32_peak_memory * 100
These metrics should only be calculated from equivalent workloads and hardware.
Benchmark Results Status
| Evaluation | Status |
|---|---|
| ONNX model loading | Tested |
| CPUExecutionProvider | Tested |
| Transformer INT4 numerical comparison | Tested |
| FP32 VAE ONNX parity | Tested |
| Initial end-to-end generation | Tested |
| INT8 VAE calibration | Initial testing |
| End-to-end visual quality | Requires further validation |
| Full FP32 versus INT4 video comparison | Pending |
| Thread-count comparison | Pending |
| ORT graph optimization comparison | Pending |
| Resolution scaling benchmark | Pending |
| 50-step reference configuration | Pending |
| Per-operator profiling | Pending |
| Repeated statistical benchmarks | Pending |
Reproducibility
For reproducible results, preserve:
- Model manifest.
- ONNX model files.
- External tensor data.
- Tokenizer files.
- Scheduler configuration.
- Runtime versions.
- Quantization configuration.
- Prompt.
- Negative prompt.
- Random seed.
- Resolution.
- Frame count.
- FPS.
- Inference steps.
- Guidance scale.
- CPU thread configuration.
The same random seed alone does not guarantee identical output across different runtimes, quantization implementations, hardware architectures or numerical precision settings.
Intended Use
This model package is intended for:
- Local text-to-video experimentation.
- CPU-based ONNX inference.
- Quantized model research.
- ONNX Runtime performance evaluation.
- Model compression experimentation.
- Video-generation pipeline development.
- Inference benchmarking and optimization.
Limitations
- CPU inference is substantially more computationally demanding than optimized GPU inference.
- INT4 quantization may introduce cumulative errors during iterative denoising.
- INT8 VAE quantization requires perceptual validation.
- Dynamic ONNX shapes do not guarantee unrestricted resolution support.
- High-resolution generation may require substantial memory.
- The current end-to-end output quality has not been fully validated.
- Reduced inference steps can degrade temporal coherence and prompt adherence.
- Performance varies by CPU architecture, memory bandwidth and ONNX Runtime version.
- This package is an experimental conversion and optimization, not an officially maintained upstream CogVideoX release.
Future Development
Inference engine
- Operator-level profiling.
- Optimized MatMulNBits execution.
- Runtime thread tuning.
- Memory allocation optimization.
- Session reuse and warm-up.
- Improved tensor buffer management.
Quantization
- Improved INT4 calibration.
- Alternative quantization block sizes.
- INT8 transformer comparison.
- Per-layer quantization analysis.
- End-to-end quality evaluation.
Video generation
- Image-to-video pipeline experiments.
- Prompt conditioning improvements.
- Negative prompt support.
- Longer video experiments.
- Temporal quality evaluation.
- Video upscaling integration.
Deployment
- FastAPI inference service.
- WebSocket generation progress.
- Asynchronous job execution.
- Model lifecycle management.
- Downloadable video artifacts.
- Resource monitoring.
License
The upstream CogVideoX-2B model is distributed under the Apache 2.0 License.
This repository contains converted and quantized model artifacts derived from the upstream model. Preserve upstream copyright and license notices, include the applicable license, and document any third-party software and conversion tooling.
Citation
@article{yang2024cogvideox,
title={CogVideoX: Text-to-Video Diffusion Models with An Expert Transformer},
author={Yang, Zhuoyi and Teng, Jiayan and Zheng, Wendi and Ding, Ming and Huang, Shiyu and Xu, Jiazheng and Yang, Yuanming and Hong, Wenyi and Feng, Guanyu and others},
journal={arXiv preprint arXiv:2408.06072},
year={2024}
}
Acknowledgements
- CogVideoX research and model team.
- Hugging Face Diffusers.
- ONNX Runtime.
- ONNX community.
- Transformers library.
Project Status
Experimental CPU-oriented ONNX conversion.
The model has undergone initial quantization validation and CPU inference testing. Further end-to-end quality evaluation, repeated performance measurements and runtime optimization are ongoing.