TinyNeuralNetwork

repository·main·Indexed 21 days ago

https://github.com/alibaba/tinyneuralnetwork

An efficient deep learning model compression framework for AI deployment on IoT and edge devices. It provides tools for neural architecture search, quantization, and model conversion, including a direct PyTorch to TFLite path and a TFLite to TensorFlow SavedModel utility (TFLite2TF). The framework also supports multiple structured channel pruning methods, including ADMM, Identity, NetAdapt, and OneShot pruning (L1, L2, FPGM, and random metrics).

Tokens
27.5K
Snippets
49
Records
126
Agent score
74%

What's inside TinyNeuralNetwork

  1. Overview of TinyNeuralNetwork modules

    main

    TinyNeuralNetwork is a deep learning model compression framework providing the following core capabilities:

    • Computational graph capture: Uses a Graph Tracer to capture PyTorch operator connectivity, automating pruning, quantization, and code generation (e.g., to models.py).
    • Dependency resolving: Uses a Graph Modifier to automatically handle subgraph mismatches when operators are modified.
    • Pruning: Implements various algorithms including OneShot (L1, L2, FPGM), ADMM, NetAdapt, Gradual, and End2End.
    • Quantization-aware training (QAT): Uses PyTorch's QAT as a backend and supports simulated bfloat16 training. It automates operator fusion and computational graph quantization.
    • Model conversion: Supports converting floating-point and quantized PyTorch models to TFLite models for deployment.
  2. Features of the TinyNeuralNetwork Converter

    main

    The converter includes the following capabilities:

    • PyTorch Support: Compatible with PyTorch 1.6+.
    • Quantization: Supports the conversion of quantized models.
    • LSTM Support: Specifically handles LSTM models which are often difficult to convert via ONNX.
    • Graph Optimizations: Includes optimization passes such as eliminating consecutive transpose and reshape operations and removing useless operators.
    • Maintainability: Written in pure Python for ease of maintenance.
  3. Model Pruning Performance Benchmarks

    main

    TinyNeuralNetwork provides various pruning strategies for optimizing neural networks, specifically targeting MobileNetV1 architectures. The framework supports different pruning algorithms and methods to balance model size (channels/FLOPs) and accuracy.

    Available Pruning Strategies

    Based on the benchmark data, the following pruning components are available:

    • OneShotPruner: A pruning method that can be combined with different importance metrics:
      • random: Random pruning.
      • l1_norm: Pruning based on L1 norm.
      • l2_norm: Pruning based on L2 norm.
      • fpgm: Pruning using FPGM.
      • hrank: Pruning using H-rank.
      • Distillation: Some OneShotPruner configurations support distillation (e.g., OneShotPruner, l2_norm, 蒸馏) to recover accuracy.
    • BNSlimingPruner: A specialized pruning strategy.
    • ADMMPruner: Pruning using the ADMM (Alternating Direction Method of Multipliers) approach, often used with l2_norm.
    • GradualPruner: A strategy for gradual pruning, often used with l2_norm.
    • RepPruner: A pruning strategy that can be combined with distillation.

    Benchmark Results Summary

    CIFAR10 Benchmarks

    For MobileNetV1-0.5 (reducing to 50% channels and 25% FLOPs), OneShotPruner with l2_norm showed the highest accuracy improvement (+0.37%).

    For MobileNetV1-0.25 (reducing to 25% channels and 6% FLOPs), GradualPruner with l2_norm provided the best accuracy retention (93.78%).

    ImageNet Benchmarks

    TinyNeuralNetwork's pruning methods (like OneShotPruner, l1_norm and GradualPruner, l2_norm) demonstrate competitive accuracy compared to original MobileNetV1 paper results and AMC (AutoML for Model Compression) benchmarks, often achieving lower accuracy loss than the baseline Google implementations when scaling down models.

  4. Understand the TinyNeuralNetwork project structure

    main

    The repository is organized into the following functional areas:

    • tinynn/: The core compression code.
      • tinynn/graph: Foundation for graph capture, resolving, quantization, code generation, and mask management.
      • tinynn/prune: Implementation of pruning algorithms.
      • tinynn/converter: Tools for model conversion.
      • tinynn/util: Utility classes.
    • examples/: Practical usage examples for each module.
    • models/: Pre-trained models for quickstart.
    • tests/: Unit tests for the framework.
  5. Understand the TinyNeuralNetwork code architecture

    main

    The repository is organized into the following functional areas:

    • tinynn/: The core model compression engine.
      • tinynn/graph/: Infrastructure for computation graph capture, analysis, quantization, code generation, and mask management.
      • tinynn/prune/: Implementation of pruning algorithms.
      • tinynn/converter/: Logic for model conversion (e.g., to TFLite).
      • tinynn/util/: General utility classes.
    • examples/: Demonstrations and usage examples for each feature.
    • models/: Pre-trained models available for rapid experimentation.
    • tests/: Unit tests for the framework.
  6. How Cross Layer Equalization (CLE) works

    main

    CLE addresses the "outlier phenomenon" where weight distributions vary greatly across channels, causing per-tensor quantization to fail (e.g., small weights being quantized to zero).

    It calculates a scale for a given channel $c_i$ and neighboring 'Conv' layers $w_1$ and $w_2$ using the formula:

    $scale = \sqrt{\frac {\lvert max({w_1}{c_i}) \rvert} {\lvert max({w_2}{c_i}) \rvert}}$

    To prevent extreme bias scaling (which occurs when one layer's max weight is near zero), a threshold parameter is used. If the sum of the absolute maximum weights of the two layers is less than the threshold, CLE is disabled for that channel.

  7. Core modules of TinyNeuralNetwork

    main

    TinyNeuralNetwork provides several key capabilities for deep learning model compression:

    • Graph Tracer (Computation Graph Capture): Captures PyTorch operator connections to enable automatic pruning and quantization. It also supports reverse code generation (codegen) to convert PyTorch models into an equivalent model.py.
    • Graph Modifier (Dependency Analysis): Manages dependencies within and between subgraphs. When a single operator is modified, the Graph Modifier automatically handles the resulting changes in related operators.
    • Pruner: Implements various automated pruning algorithms including OneShot (L1, L2, FPGM), ADMM, NetAdapt, Gradual, and End2End (to be released incrementally).
    • Quantization Training: Uses PyTorch's QAT (Quantization Aware Training) as a backend with extended support for BF16 training. It automates operator fusion and computation graph quantization, which typically requires significant manual effort in standard PyTorch implementations.
    • Model Converter: Supports converting both floating-point and quantized PyTorch models into TFLite format for on-device deployment.
  8. How the graph tracer handles constants and multiple models

    main

    The model_tracer context manager provides several flexible behaviors:

    • Instantiation: The model being traced can be instantiated either inside or outside the with model_tracer(): block.
    • Multiple Models: You can trace multiple different models within a single with block.
    • Runtime Constants: The tracer supports runtime-defined constants. If a constant is too large, it will automatically be transformed into a parameter.
  9. Understand the TinyNeuralNetwork quantization workflow

    main

    TinyNeuralNetwork simplifies the standard PyTorch quantization process by automating several manual steps.

    Standard PyTorch Workflow (Manual):

    1. Manually insert QuantStub and DeQuantStub into the forward function.
    2. Replace arithmetic operations (e.g., add, mul, cat) with torch.nn.quantized.FloatFunctional operators.
    3. Manually write a fuse_model function to fuse operators (e.g., Conv2D + BatchNorm2D $\rightarrow$ ConvBN2D).
    4. Call prepare_qat to convert the graph to a quantized graph.
    5. Deployment is difficult because quantized models are often limited to TorchScript and cannot easily convert to ONNX or TFLite.

    TinyNeuralNetwork Workflow (Automated):

    • Code Generation: Automatically generates new code equivalent to manual QuantStub insertion and FloatFunctional replacement.
    • Intelligent Preparation: The prepare_qat function automatically handles operator fusion and mixed-precision analysis.
    • Simplified Deployment: Provides conversion from TorchScript to TFLite (supporting both floating-point and quantized models), making edge deployment easier.
  10. Set up DLContext for NetAdapt training and Fine-tuning

    main

    The DLContext object is used to provide the necessary training and validation components to the pruner. Depending on whether you are performing the main NetAdapt training or the final fine-tuning, different parameters are required.

    For NetAdapt Training

    You must provide:

    • train_loader (Dataloader): Training data loader.
    • val_loader (Dataloader): Validation data loader.
    • criterion (lambda): A loss function with signature (output: Tensor, target: Tensor) -> Tensor.
    • optimizer (Optimizer): The optimizer for training.

    For Fine-tuning

    You must provide:

    • train_loader (Dataloader): Training data loader.
    • val_loader (Dataloader): Validation data loader.
    • criterion (lambda): A loss function with signature (output: Tensor, target: Tensor) -> Tensor.
    • optimizer (Optimizer): The optimizer for training.
    • scheduler (LR_Scheduler, optional): An optional learning rate scheduler for the optimizer.
  11. Convert and use LSTM/GRU models in TFLite

    main

    Converting RNNs to TFLite can be done in two ways:

    1. Unrolled RNN (unroll_rnn=True)

    This translates the RNN into a series of standard operations. This is the easiest method but results in a more complex computation graph.

    2. Single Operator (UnidirectionalLSTM)

    To use a single UnidirectionalLSTM operator, you must manually manage the state tensors.

    Important: When exporting from PyTorch, you must delete the LSTM state inputs and outputs from the model's inputs and outputs to simulate TensorFlow's behavior (where states are persistent Variables).

    Usage Scenarios:

    • Non-streaming: Call interpreter.reset_all_variables() in the TFLite Interpreter before each invoke() to reset states to zero.
    • Streaming: You must manually read/write state variables. Use tinynn.converter.utils.tflite.parse_lstm_states(tflite_path) to find the indices of the state tensors, then use get_tensor and set_tensor to manage them. Note that state variables are 2D with shape [batch_size, hidden_size or input_size].