We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

必須Cookiesのみ
すべて同意

Demos

Demo for TensorFlow Quant_INT8-8 Quantization in Non-Training Mode

Preparing the Environment

For details about how to prepare the environment, refer to Preparing the Environment to install TensorFlow and its dependencies.

Configuring the Model

  • Prepare the quantization model.

    Load the .pb file of the baseline model to dopt_tf_py3/demo/quant8-8/notrain/tensorflow_mnist/basemodel/. This path contains the MNIST baseline model file mnist.pb.

  • Prepare the input data for quantization.

    Load the image or binary calibration dataset to dopt_tf_py3/demo/quant8-8/notrain/tensorflow_mnist/mnist_test/ by referring to Quantizing the Model. This path contains a preset image calibration dataset.

Quantizing the Model

Run run_release.sh in dopt_tf_py3/demo/quant8-8/notrain/tensorflow_mnist/.

The quantized PB model and quantization configuration file are stored in dopt_tf_py3/demo/quant8-8/notrain/tensorflow_mnist. Run the demo and the following files will be generated:

Demo for PyTorch Quant_INT8-8 Quantization in Non-Training Mode

Preparing the Environment

For details about how to prepare the environment, refer to Preparing the Environment to install PyTorch and its dependencies.

Configuring the Model

  • Prepare the quantization model.

    Save the model definition file (.py) and model parameter file of the baseline model to dopt_pytorch_py3/demo/quant8-8/notrain/pytorch_mnist/.

    The mnist.py baseline model definition file and the model parameter file mnist.pkl have been stored in the path.

  • Prepare the input data for quantization.

    Load the image or binary calibration dataset to dopt_pytorch_py3/demo/quant8-8/notrain/pytorch_mnist/ by referring to Quantizing the Model.

Quantizing the Model

Run run_release.sh in dopt_pytorch_py3/demo/quant8-8/notrain/pytorch_mnist/.

In dopt_pytorch_py3/demo/quant8-8/notrain/pytorch_mnist/, you can find a PyTorch non-training quantization demo file, as shown in the following figure:

Demo for ONNX Quant_INT8-8 Quantization in Non-Training Mode

Preparing the Environment

For details about how to prepare the environment, refer to Preparing the Environment to install ONNX and its dependencies.

Sample Code

Add the dopt_onnx_py3 directory to the system environment and execute it in the terminal environment.

Collapse
Word wrap
Dark theme
Copy code
  1. python3 ./dopt_so.py \
  2. --framework 5 \
  3. --mode 0 \
  4. --model "./resnet18_matmul.onnx" \ ## ONNX model to be quantized.
  5. --cal_conf "./config.prototxt" \ ## Calibration set configuration file.
  6. --output "./resnet18_matmul_quant.onnx" \ ## Quantized ONNX file.
  7. --input_shape input:1,3,128,128 \ ## Shape of the floating-point model's input.
  8. --compress_conf ./mnist_param ## Quantization configuration file generated by the dopt tool.

For details about the configuration of ./config.prototxt, please refer to How to Use the Configuration File.

Collapse
Word wrap
Dark theme
Copy code
  1. strategy: 'Quant_INT8-8'
  2. device: USE_CPU
  3. preprocess_parameter:
  4. {
  5. input_type: BINARY
  6. input_file_path: './input1.bin'
  7. }

Demo for TensorFlow Quant_INT8-8 Plugin-based Quantization

Preparing the Environment

Prepare the TensorFlow environment by referring to Preparing the TensorFlow Environment. Install TensorFlow-gpu 2.8.0 and its necessary dependencies.

Sample Code

Collapse
Word wrap
Dark theme
Copy code
  1. import sys
  2. sys.path.append(".../dopt_tf_py3") ## The path should be an absolute path.
  3. def generate_config():
  4. with tf.Session(config=config) as sess:
  5. build_tf_model() ## Customize the graph of the TensorFlow model to be quantized. Only the topology will be built, and the weight will not be loaded.
  6. from dopt.dopt_tf.opt_main import generate_config_file
  7. generate_config_file(sess, dst_path="./config_gen.json")
  8. def train_model():
  9. with tf.Session(config=config) as sess:
  10. build_tf_model() ## Customize the graph of the TensorFlow model to be quantized. Only the topology will be built, and the weight will not be loaded.
  11. from dopt.dopt_tf.opt_main import optimize_model
  12. quant_flag = tf.placeholder(tf.int32)
  13. is_train_flag = tf.placeholder(tf.bool, name='is_train')
  14. ## Quantize the model. The graph will automatically be modified in tf.get_default_graph().
  15. optimize_model(
  16. sess,
  17. "./config_gen.json",
  18. is_train_flag,
  19. quant_flag
  20. )
  21. ## Load the model weight after calling optimize_model.
  22. saver = tf.Saver()
  23. saver.restore(ckpt)
  24. tf.global_variables_initializer().run()
  25. ## train model
  26. for i in range(...):
  27. optimizer = ...
  28. feed_dict[is_train_flag] = True
  29. feed_dict[quant_flag] = 1
  30. sess.run(train_op, feed_dict)
  31. ## eval model
  32. feed_dict[is_train_flag] = False
  33. feed_dict[quant_flag] = 1
  34. sess.run(output, feed_dict)
  35. evaluate_output(output)
  36. def calibrate_model():
  37. with tf.Session(config=config) as sess:
  38. build_tf_model() ## Customize the graph of the TensorFlow model to be quantized. Only the topology will be built, and the weight will not be loaded.
  39. from dopt.dopt_tf.opt_main import optimize_model, set_calibrate_state
  40. quant_flag = tf.placeholder(tf.int32)
  41. is_train_flag = tf.placeholder(tf.bool, name='is_train')
  42. ## Quantize the model. The graph will automatically be modified in tf.get_default_graph().
  43. optimize_model(
  44. sess,
  45. "./config_gen.json",
  46. is_train_flag,
  47. quant_flag
  48. )
  49. ## Load the model weight after calling optimize_model.
  50. saver = tf.Saver()
  51. saver.restore(ckpt)
  52. calibration_mode = True
  53. set_calibrate_state(sess, calibration_mode )
  54. ## eval model
  55. feed_dict[is_train_flag] = False
  56. feed_dict[quant_flag] = 1
  57. sess.run(output, feed_dict)
  58. evaluate_output(output)
  59. def generate_params():
  60. with tf.Session(config=config) as sess:
  61. build_tf_model()
  62. from dopt.dopt_tf.opt_main import generate_final_model
  63. generate_final_model(
  64. sess,
  65. config_file = "./config_gen.json",
  66. output_name_list = ["output"],
  67. ckpt_file = "train_ckpt_path",
  68. output_dir = "./output_dir"
  69. )
  70. if __name__ == "__main__":
  71. ## step 1
  72. ## Modify the configuration.
  73. generate_config()
  74. ## step 2
  75. ## Train the model until it meets the requirements.
  76. train_model() ## Retrain the model.
  77. ## calibrate_model() ## Calibrate the model.
  78. ## step 3
  79. ## Extract parameters for subsequent model deployment.
  80. generate_params()

Demo for PyTorch Quant_INT8-8 Plugin-based Quantization

Preparing the Environment

Prepare the PyTorch environment by referring to Preparing the PyTorch Environment. Install PyTorch-gpu 1.11 and its necessary dependencies.
Collapse
Word wrap
Dark theme
Copy code
  1. import sys
  2. sys.path.append(".../dopt_tf_py3") ## The path should be an absolute path.
  3. def generate_config():
  4. model = build_torch_model() ## Floating-point model to be quantized.
  5. generate_config_file(model, input_shape, dst_path="./config_gen.json") # model:torch.nn.Module, input_shape : "input1:input1.shape;input2:input2.shape"
  6. return model
  7. def train_model():
  8. model = build_torch_model() ## Floating-point model to be quantized.
  9. from dopt.dopt_torch.opt_main import optimize_model
  10. model.load_state_dict(state) ## Load parameters for the floating-point model.
  11. ## Call optimize_model to quantize the model.
  12. quanted_model = optimize_model(model, config_path)
  13. ## train model
  14. quant_loss = get_quant_loss(quant_model)
  15. optimizer = torch.optim.SGD(quanted_model.parameters(), lr=0.001, momentum=0.9) ## Assumes that the SGD optimizer is used.
  16. for input_data, label in range(...):
  17. optimizer.zero_grad()
  18. outputs = model(input_data)
  19. loss = loss_fn(outputs, label) ## loss_fn indicates the loss of the original floating-point network training.
  20. total_loss = loss + quant_weight * quant_loss ## quant_weight indicates the proportion of the quantization loss.
  21. loss.backward()
  22. optimizer.step()
  23. def calibrate_model():
  24. model = build_torch_model() ## Floating-point model to be quantized.
  25. from dopt.dopt_torch.opt_main import optimize_model, set_calibrate_state
  26. model.load_state_dict(state) ## Load parameters for the floating-point model.
  27. ## Call optimize_model to quantize the model.
  28. quanted_model = optimize_model(model, config_path)
  29. calibrate_mode = True
  30. set_calibrate_state(model, calibrate_mode)
  31. for input_data, label in range(...):
  32. outputs = model(input_data)
  33. def generate_params():
  34. model = build_torch_model()
  35. from dopt.dopt_torch.opt_main import generate_final_model
  36. generate_final_model(model,
  37. config_file,
  38. pth_file="quant.pth",
  39. output_dir="./results_dir")
  40. if __name__ == "__main__":
  41. ## step 1
  42. ## Modify the configuration.
  43. generate_config()
  44. ## step 2
  45. ## Train the model until it meets the requirements.
  46. train_model()
  47. ## calibrate_model() ## Non-training mode.
  48. ## step 3
  49. ## Extract parameters for subsequent model deployment.
  50. generate_params()

TensorFlow NASEA NAS Demo

NASEA Classification Network Demo

The classification network demo is stored in tools_dopt/dopt_tf_py3/demo/nas_ea/ea_cls_imagenet and contains the following files.

  • blocks.so: A search space file.
  • readme.md: A search training guide.
  • run_release.sh: A script that starts the search.
  • scen.yaml: A configuration item.
  • user_module.py: Customized APIs of the tool.

The procedure is as follows:

  1. Prepare an ImageNet dataset (in TFRecord format) and change the dataset directory in scen.yaml.
  2. For details, see Preparing the Environment.
  3. Load the dependent open-source code.

    1. Go to the demo directory of the classification network.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd tools_dopt/dopt_tf_py3/demo/nas_ea/ea_cls_imagenet
    1. Download the open-source code.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git clone https://github.com/Tensorflow/models.git
    1. Go to the directory of the open-source code.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd models
    1. Switch to the specified version:
      • If TensorFlow 1.12.0 is used, run the following command:
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git checkout v1.12.0
      • If TensorFlow 2.1.0 is used, run the following command:
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git checkout v2.1.0
    2. Return to the demo directory of the classification network.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd ..
    3. Set the default path of PYTHONPATH.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. export PYTHONPATH=$PYTHONPATH:`pwd`/models/
    NOTICE

    Each time you open the terminal, you need to run the command again. Alternatively, add the command to the ~/.bashrc file and run source ~/.bashrc.

  4. Configure the scen.yaml file in the demo. For details, see Configuring Search Parameters. The scen.yaml file provides recommended parameters. You can modify them as required.
  5. Modify the user_module.py file in the demo. For details about the model API definition, see Custom TensorFlow APIs. The user_module.py file provides recommended configurations. You can modify them as required.
  6. Execute the run_release.sh script. Multiple model_arch_result_*.py files will be generated in results. You can select a proper network architecture for training based on the information provided in log_classification. For details about subsequent training, see readme.md.

NASEA Detection Network Demo

The detection network demo is stored in tools_dopt/dopt_tf_py3/demo/nas_ea/ea_det_coco and contains the following files.

  • blocks.so: A search space file.
  • pre_train.yaml: A configuration item for pre-training.
  • readme.md: A search training guide.
  • run_release.sh: A script that starts the search.
  • scen.yaml: A configuration item.
  • user_module.py: Customized APIs of the tool.

The procedure is as follows:

  1. Prepare datasets, including the ImageNet dataset (in TFRecord format) used for pre-training and the COCO dataset (in original format) used for training. If a pre-trained CKPT file is available, you do not need to prepare the ImageNet dataset. Change the dataset directory in the scen.yaml file by referring to Configuring Search Parameters.
  2. For details, see Preparing the Environment.
  3. Load the dependent open-source code.

    1. Go to the demo directory of the detection network.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd tools_dopt/dopt_tf_py3/demo/nas_ea/ea_det_coco
    2. Download the open-source code.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git clone https://github.com/pierluigiferrari/ssd_keras.git
      2. git clone https://github.com/Tensorflow/models.git
    3. Go to the directory of the open-source code.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd ssd_keras
    4. Switch to the specified version:
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git checkout -b v0.9.0
    5. Return to the demo directory of the detection network.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd ..
    6. Go to the models open-source code directory.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd models
    7. Switch the models to the specified version:

      If TensorFlow 1.12.0 is used, run the following command:

      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git checkout v1.12.0

      If TensorFlow 2.1.0 is used, run the following command:

      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git checkout v2.1.0
    8. Go to the models open-source code directory.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd models
    9. Set the default path of PYTHONPATH.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. export PYTHONPATH=$PYTHONPATH:`pwd`/models/
    10. Modify related open-source files by referring to Step 1 to 4 in readme.md.

  4. Configure the scen.yaml and pre_train.yaml files in the demo directory. For details, see Configuring Search Parameters. The scen.yaml file provides recommended parameters. You can modify them as required.
  5. Modify the user_module.py file in the demo. For details about the model API definition, see Custom TensorFlow APIs. The user_module.py file provides recommended configurations. You can modify them as required.
  6. Execute the run_release.sh script. Multiple model_arch_result_*.py files will be generated in results. You can select a proper network architecture for training based on the information provided in log_detection. For details about subsequent training, see readme.md.

NASEA Segmentation Network Demo

The segmentation network demo is stored in tools_dopt/dopt_tf_py3/demo/nas_ea/ea_seg_voc and contains the following files.

  • blocks.so: A search space file.
  • pre_train.yaml: A configuration item for pre-training.
  • readme.md: A search training guide.
  • run_release.sh: A script that starts the search.
  • scen.yaml: A configuration item.
  • user_module.py: Customized APIs of the tool.

The procedure is as follows:

  1. Prepare datasets, including the ImageNet dataset (in TFRecord format) used for pre-training and the VOC dataset (in TFRecord format) used for training. If a pre-trained CKPT file is available, you do not need to prepare the ImageNet dataset. Change the dataset directory in the scen.yaml file by referring to Configuring Search Parameters.
  2. For details, see Preparing the Environment.
  3. Load the dependent open-source code.

    1. Go to the demo directory of the segmentation network.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd tools_dopt/dopt_tf_py3/demo/nas_ea/ea_seg_voc
    2. Download the open-source code.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git clone https://github.com/Tensorflow/models.git
    3. Go to the directory of the open-source code.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd models
    4. Switch to the specified version:
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. git checkout v1.13.0
    5. Return to the demo directory of the segmentation network.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. cd ..
    6. Set the default path of PYTHONPATH.
      Collapse
      Word wrap
      Dark theme
      Copy code
      1. export PYTHONPATH=$PYTHONPATH:`pwd`/models/research:`pwd`/models/research/slim
    7. If TensorFlow 2.1.0 is used, run the following command:
      1. Create models_tf2.1 and access the folder.
        Collapse
        Word wrap
        Dark theme
        Copy code
        1. mkdir models_tf2.1
        2. cd models_tf2.1
      2. Download the open-source implementation code.
        Collapse
        Word wrap
        Dark theme
        Copy code
        1. git clone https://github.com/Tensorflow/models.git
      3. Go to the directory of the open-source code.
        Collapse
        Word wrap
        Dark theme
        Copy code
        1. cd models
      4. Switch to the specified version:
        Collapse
        Word wrap
        Dark theme
        Copy code
        1. git checkout v2.1.0
      5. Return to the models_tf2.1 folder.
        Collapse
        Word wrap
        Dark theme
        Copy code
        1. cd ..
      6. Set the default path of PYTHONPATH.
        Collapse
        Word wrap
        Dark theme
        Copy code
        1. export PYTHONPATH=$PYTHONPATH:`pwd`/models/
        NOTICE

        Each time you open the terminal, you need to run the command again. Alternatively, add the command to the ~/.bashrc file and run source ~/.bashrc.

    8. Modify the open-source implementation code according to the procedure specified in readme.md.

  4. Configure the scen.yaml and pre_train.yaml files in the demo directory. For details, see Configuring Search Parameters. The scen.yaml file provides recommended parameters. You can modify them as required.
  5. Modify the user_module.py file in the demo. For details about the model API definition, see Custom TensorFlow APIs. The user_module.py file provides recommended configurations. You can modify them as required.
  6. Execute the run_release.sh script. Multiple model_arch_result_*.py files will be generated in results. You can select a proper network architecture for training based on the information provided in log_segmentation. For details about subsequent training, see readme.md.

PyTorch NASEA NAS Demo

NASEA Classification Network

The classification network demo is stored in tools_dopt/dopt_pytorch_py3/demo/nas_ea/ea_cls_imagenet_pytorch and contains the following files.

  • blocks.so: A search space file.
  • readme.md: A search training guide.
  • run_release.sh: A script that starts the search.
  • scen.yaml: A configuration item.
  • user_module.py: Customized APIs of the tool.

The procedure is as follows:

  1. Prepare an ImageNet dataset (in original format) and change the dataset directory in scen.yaml.
  2. For details, see Preparing the Environment.
  3. Configure the scen.yaml file in the demo. For details, see Configuring Search Parameters. The scen.yaml file provides recommended parameters. You can modify them as required.
  4. Modify the user_module.py file in the demo. For details about the model API definition, see Custom PyTorch APIs. The user_module.py file provides recommended configurations. You can modify them as required.
  5. Execute the run_release.sh script. Multiple model_arch_result_*.py files will be generated in results. You can select a proper network architecture for training based on the information provided in log_classification. For details about subsequent training, see readme.md.

NASEA Segmentation Network Demo

The segmentation network demo is stored in tools_dopt/dopt_pytorch_py3/demo/nas_ea/ea_seg_voc_pytorch and contains the following files.

  • blocks.so: A search space file.
  • pre_train.yaml: A configuration item for pre-training.
  • readme.md: A search training guide.
  • run_release.sh: A script that starts the search.
  • scen.yaml: A configuration item.
  • user_module.py: Customized APIs of the tool.

The procedure is as follows:

  1. Prepare datasets, including the ImageNet dataset (in original format) used for pre-training and the VOC dataset (in original format) used for training. If a pre-trained CKPT file is available, you do not need to prepare the ImageNet dataset. Change the dataset directory in the scen.yaml file by referring to Configuring Search Parameters.
  2. For details, see Preparing the Environment.
  3. Load the dependent open source code. For details, please refer to tools_dopt/dopt_pytorch_py3/demo/nas_ea/ea_seg_voc_pytorch/readme.md.
  4. Configure the scen.yaml and pre_train.yaml files in the demo directory. For details, see Configuring Search Parameters. The scen.yaml file provides recommended parameters. You can modify them as required.
  5. Modify the user_module.py file in the demo. For details about the model API definition, see Custom PyTorch APIs. The user_module.py file provides recommended configurations. You can modify them as required.
  6. Execute the run_release.sh script. Multiple model_arch_result_*.py files will be generated in results. You can select a proper network architecture for training based on the information provided in log_segmentation. For details about subsequent training, see readme.md.
Search in Guides
Enter a keyword.