![]() | ![]() | ![]() | ![]() |
ยินดีต้อนรับสู่คู่มือที่ครอบคลุมสำหรับการฝึกอบรม Keras quantization Awareness
หน้านี้จัดทำเอกสารกรณีการใช้งานต่างๆ และแสดงวิธีใช้ API สำหรับแต่ละกรณี เมื่อคุณทราบว่า API ที่คุณต้องการหาพารามิเตอร์และรายละเอียดในระดับต่ำใน เอกสาร API
- หากคุณต้องการที่จะเห็นประโยชน์ของการฝึกอบรมตระหนักถึงควอนและสิ่งที่เป็นได้รับการสนับสนุนให้ดู ภาพรวม
- สำหรับตัวอย่างแบบ end-to-end เดียวดู quantization ตัวอย่างเช่นการฝึกอบรมตระหนักถึง
ครอบคลุมกรณีการใช้งานต่อไปนี้:
- ปรับใช้โมเดลด้วย quantization 8 บิตด้วยขั้นตอนเหล่านี้
- กำหนดแบบจำลองการรับรู้เชิงปริมาณ
- สำหรับรุ่น Keras HDF5 เท่านั้น ให้ใช้ลอจิกจุดตรวจพิเศษและดีซีเรียลไลเซชัน การฝึกอบรมเป็นอย่างอื่นมาตรฐาน
- สร้างแบบจำลองเชิงปริมาณจากตัวที่รับรู้การหาปริมาณ
- ทดลองกับการหาปริมาณ
- สิ่งใดสำหรับการทดลองไม่มีเส้นทางที่รองรับในการทำให้ใช้งานได้
- เลเยอร์ Keras ที่กำหนดเองอยู่ภายใต้การทดลอง
ติดตั้ง
สำหรับการค้นหา API ที่คุณต้องการและทำความเข้าใจวัตถุประสงค์ คุณสามารถเรียกใช้แต่ข้ามการอ่านส่วนนี้
! pip uninstall -y tensorflow
! pip install -q tf-nightly
! pip install -q tensorflow-model-optimization
import tensorflow as tf
import numpy as np
import tensorflow_model_optimization as tfmot
import tempfile
input_shape = [20]
x_train = np.random.randn(1, 20).astype(np.float32)
y_train = tf.keras.utils.to_categorical(np.random.randn(1), num_classes=20)
def setup_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(20, input_shape=input_shape),
tf.keras.layers.Flatten()
])
return model
def setup_pretrained_weights():
model= setup_model()
model.compile(
loss=tf.keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy']
)
model.fit(x_train, y_train)
_, pretrained_weights = tempfile.mkstemp('.tf')
model.save_weights(pretrained_weights)
return pretrained_weights
def setup_pretrained_model():
model = setup_model()
pretrained_weights = setup_pretrained_weights()
model.load_weights(pretrained_weights)
return model
setup_model()
pretrained_weights = setup_pretrained_weights()
2021-10-01 11:29:25.336019: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected
กำหนดแบบจำลองการรับรู้เชิงปริมาณ
โดยการกำหนดรูปแบบในวิธีต่อไปนี้มีเส้นทางที่สามารถใช้ได้กับการใช้งานในการแบ็กเอนด์ที่ระบุไว้ใน หน้าภาพรวม ตามค่าเริ่มต้น จะใช้การควอนไทซ์แบบ 8 บิต
หาปริมาณทั้งรุ่น
กรณีการใช้งานของคุณ:
- ไม่รองรับรุ่นย่อย
เคล็ดลับเพื่อความแม่นยำของแบบจำลองที่ดีขึ้น:
- ลองใช้ "Quantize บางเลเยอร์" เพื่อข้ามการหาปริมาณเลเยอร์ที่ลดความแม่นยำมากที่สุด
- โดยทั่วไปแล้วจะเป็นการดีกว่าที่จะปรับแต่งด้วยการฝึกอบรมการรับรู้เชิงปริมาณมากกว่าการฝึกตั้งแต่เริ่มต้น
เพื่อให้รูปแบบทั้งตระหนักถึง quantization ใช้ tfmot.quantization.keras.quantize_model
โมเดล
base_model = setup_model()
base_model.load_weights(pretrained_weights) # optional but recommended for model accuracy
quant_aware_model = tfmot.quantization.keras.quantize_model(base_model)
quant_aware_model.summary()
Model: "sequential_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer (QuantizeLay (None, 20) 3 er) quant_dense_2 (QuantizeWrap (None, 20) 425 perV2) quant_flatten_2 (QuantizeWr (None, 20) 1 apperV2) ================================================================= Total params: 429 Trainable params: 420 Non-trainable params: 9 _________________________________________________________________
หาจำนวนชั้น
การหาปริมาณแบบจำลองอาจส่งผลเสียต่อความแม่นยำ คุณสามารถเลือกหาปริมาณเลเยอร์ของแบบจำลองเพื่อสำรวจความแตกต่างระหว่างความแม่นยำ ความเร็ว และขนาดของแบบจำลอง
กรณีการใช้งานของคุณ:
- ในการปรับใช้กับแบ็กเอนด์ที่ทำงานได้ดีกับโมเดลที่มีการกำหนดปริมาณอย่างสมบูรณ์เท่านั้น (เช่น EdgeTPU v1, DSP ส่วนใหญ่) ให้ลองใช้ "Quantize ทั้งโมเดล"
เคล็ดลับเพื่อความแม่นยำของแบบจำลองที่ดีขึ้น:
- โดยทั่วไปแล้วจะเป็นการดีกว่าที่จะปรับแต่งด้วยการฝึกอบรมการรับรู้เชิงปริมาณมากกว่าการฝึกตั้งแต่เริ่มต้น
- ลองหาจำนวนชั้นที่ตามมาแทนที่จะเป็นชั้นแรก
- หลีกเลี่ยงการหาปริมาณชั้นวิกฤต (เช่น กลไกการเอาใจใส่)
ในตัวอย่างด้านล่าง quantize เพียง Dense
ชั้น
# Create a base model
base_model = setup_model()
base_model.load_weights(pretrained_weights) # optional but recommended for model accuracy
# Helper function uses `quantize_annotate_layer` to annotate that only the
# Dense layers should be quantized.
def apply_quantization_to_dense(layer):
if isinstance(layer, tf.keras.layers.Dense):
return tfmot.quantization.keras.quantize_annotate_layer(layer)
return layer
# Use `tf.keras.models.clone_model` to apply `apply_quantization_to_dense`
# to the layers of the model.
annotated_model = tf.keras.models.clone_model(
base_model,
clone_function=apply_quantization_to_dense,
)
# Now that the Dense layers are annotated,
# `quantize_apply` actually makes the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
quant_aware_model.summary()
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.iter WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_1 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_2 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.decay WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.learning_rate WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'm' for (root).layer_with_weights-0.kernel WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'm' for (root).layer_with_weights-0.bias WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'v' for (root).layer_with_weights-0.kernel WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'v' for (root).layer_with_weights-0.bias WARNING:tensorflow:A checkpoint was restored (e.g. tf.train.Checkpoint.restore or tf.keras.Model.load_weights) but not all checkpointed values were used. See above for specific issues. Use expect_partial() on the load status object, e.g. tf.train.Checkpoint.restore(...).expect_partial(), to silence these warnings, or use assert_consumed() to make the check explicit. See https://www.tensorflow.org/guide/checkpoint#loading_mechanics for details. Model: "sequential_3" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_1 (QuantizeL (None, 20) 3 ayer) quant_dense_3 (QuantizeWrap (None, 20) 425 perV2) flatten_3 (Flatten) (None, 20) 0 ================================================================= Total params: 428 Trainable params: 420 Non-trainable params: 8 _________________________________________________________________
ในขณะที่ตัวอย่างนี้ใช้ประเภทของชั้นที่จะตัดสินใจว่าจะ quantize วิธีที่ง่ายที่สุดที่จะ quantize ชั้นโดยเฉพาะอย่างยิ่งคือการตั้งค่าของ name
คุณสมบัติและมองหาชื่อที่อยู่ใน clone_function
print(base_model.layers[0].name)
dense_3
อ่านง่ายขึ้นแต่อาจลดความแม่นยำของแบบจำลองลง
วิธีนี้เข้ากันไม่ได้กับการปรับละเอียดด้วยการฝึกอบรมการรับรู้เชิงปริมาณ ซึ่งเป็นสาเหตุที่ทำให้แม่นยำน้อยกว่าตัวอย่างข้างต้น
ตัวอย่างการใช้งาน
# Use `quantize_annotate_layer` to annotate that the `Dense` layer
# should be quantized.
i = tf.keras.Input(shape=(20,))
x = tfmot.quantization.keras.quantize_annotate_layer(tf.keras.layers.Dense(10))(i)
o = tf.keras.layers.Flatten()(x)
annotated_model = tf.keras.Model(inputs=i, outputs=o)
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
# For deployment purposes, the tool adds `QuantizeLayer` after `InputLayer` so that the
# quantized model can take in float inputs instead of only uint8.
quant_aware_model.summary()
Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 20)] 0 quantize_layer_2 (QuantizeL (None, 20) 3 ayer) quant_dense_4 (QuantizeWrap (None, 10) 215 perV2) flatten_4 (Flatten) (None, 10) 0 ================================================================= Total params: 218 Trainable params: 210 Non-trainable params: 8 _________________________________________________________________
ตัวอย่างตามลำดับ
# Use `quantize_annotate_layer` to annotate that the `Dense` layer
# should be quantized.
annotated_model = tf.keras.Sequential([
tfmot.quantization.keras.quantize_annotate_layer(tf.keras.layers.Dense(20, input_shape=input_shape)),
tf.keras.layers.Flatten()
])
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
quant_aware_model.summary()
Model: "sequential_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_3 (QuantizeL (None, 20) 3 ayer) quant_dense_5 (QuantizeWrap (None, 20) 425 perV2) flatten_5 (Flatten) (None, 20) 0 ================================================================= Total params: 428 Trainable params: 420 Non-trainable params: 8 _________________________________________________________________
ด่านและดีซีเรียลไลซ์
กรณีการใช้งานของคุณ: รหัสนี้เป็นสิ่งจำเป็นสำหรับรูปแบบรูปแบบ HDF5 (ไม่ใช่ HDF5 น้ำหนักหรือรูปแบบอื่น ๆ )
# Define the model.
base_model = setup_model()
base_model.load_weights(pretrained_weights) # optional but recommended for model accuracy
quant_aware_model = tfmot.quantization.keras.quantize_model(base_model)
# Save or checkpoint the model.
_, keras_model_file = tempfile.mkstemp('.h5')
quant_aware_model.save(keras_model_file)
# `quantize_scope` is needed for deserializing HDF5 models.
with tfmot.quantization.keras.quantize_scope():
loaded_model = tf.keras.models.load_model(keras_model_file)
loaded_model.summary()
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.iter WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_1 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_2 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.decay WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.learning_rate WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'm' for (root).layer_with_weights-0.kernel WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'm' for (root).layer_with_weights-0.bias WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'v' for (root).layer_with_weights-0.kernel WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'v' for (root).layer_with_weights-0.bias WARNING:tensorflow:A checkpoint was restored (e.g. tf.train.Checkpoint.restore or tf.keras.Model.load_weights) but not all checkpointed values were used. See above for specific issues. Use expect_partial() on the load status object, e.g. tf.train.Checkpoint.restore(...).expect_partial(), to silence these warnings, or use assert_consumed() to make the check explicit. See https://www.tensorflow.org/guide/checkpoint#loading_mechanics for details. WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model. WARNING:tensorflow:No training configuration found in the save file, so the model was *not* compiled. Compile it manually. Model: "sequential_5" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_4 (QuantizeL (None, 20) 3 ayer) quant_dense_6 (QuantizeWrap (None, 20) 425 perV2) quant_flatten_6 (QuantizeWr (None, 20) 1 apperV2) ================================================================= Total params: 429 Trainable params: 420 Non-trainable params: 9 _________________________________________________________________
สร้างและปรับใช้โมเดลเชิงปริมาณ
โดยทั่วไป ให้อ้างอิงเอกสารสำหรับแบ็กเอนด์การปรับใช้ที่คุณจะใช้
นี่คือตัวอย่างสำหรับแบ็กเอนด์ TFLite
base_model = setup_pretrained_model()
quant_aware_model = tfmot.quantization.keras.quantize_model(base_model)
# Typically you train the model here.
converter = tf.lite.TFLiteConverter.from_keras_model(quant_aware_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
quantized_tflite_model = converter.convert()
1/1 [==============================] - 0s 269ms/step - loss: 16.1181 - accuracy: 0.0000e+00 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.iter WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_1 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_2 WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.decay WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.learning_rate WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'm' for (root).layer_with_weights-0.kernel WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'm' for (root).layer_with_weights-0.bias WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'v' for (root).layer_with_weights-0.kernel WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer's state 'v' for (root).layer_with_weights-0.bias WARNING:tensorflow:A checkpoint was restored (e.g. tf.train.Checkpoint.restore or tf.keras.Model.load_weights) but not all checkpointed values were used. See above for specific issues. Use expect_partial() on the load status object, e.g. tf.train.Checkpoint.restore(...).expect_partial(), to silence these warnings, or use assert_consumed() to make the check explicit. See https://www.tensorflow.org/guide/checkpoint#loading_mechanics for details. 2021-10-01 11:29:28.281011: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them. WARNING:absl:Found untraced functions such as dense_7_layer_call_fn, dense_7_layer_call_and_return_conditional_losses, flatten_7_layer_call_fn, flatten_7_layer_call_and_return_conditional_losses, dense_7_layer_call_fn while saving (showing 5 of 10). These functions will not be directly callable after loading. INFO:tensorflow:Assets written to: /tmp/tmps5i7uwfh/assets INFO:tensorflow:Assets written to: /tmp/tmps5i7uwfh/assets 2021-10-01 11:29:29.254470: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:363] Ignored output_format. 2021-10-01 11:29:29.254516: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:366] Ignored drop_control_dependency. WARNING:absl:Buffer deduplication procedure will be skipped when flatbuffer library is not properly loaded 2021-10-01 11:29:29.360670: W tensorflow/compiler/mlir/lite/flatbuffer_export.cc:704] Cannot get mac count for %2 = "tfl.fully_connected"(%0, %1, %cst_0) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor<?x20x!quant.uniform<i8:f32, 3.9215686274509805E-9:-1>>, tensor<*x!quant.uniform<i8<-127:127>:f32, 0.047244094488188976>>, none) -> tensor<?x20x!quant.uniform<i8:f32, 0.047058823529411764>>
ทดลองกับการหาปริมาณ
กรณีการใช้งานของคุณ: การใช้ API ของวิธีการดังต่อไปนี้ว่ามีการสนับสนุนเส้นทางที่จะใช้งาน ตัวอย่างเช่น การแปลง TFLite และการใช้งานเคอร์เนลรองรับเฉพาะ quantization 8 บิตเท่านั้น คุณลักษณะนี้ยังอยู่ในขั้นทดลองและไม่สามารถใช้งานร่วมกันได้แบบย้อนหลัง
-
tfmot.quantization.keras.QuantizeConfig
-
tfmot.quantization.keras.quantizers.Quantizer
-
tfmot.quantization.keras.quantizers.LastValueQuantizer
-
tfmot.quantization.keras.quantizers.MovingAverageQuantizer
ตั้งค่า: DefaultDenseQuantizeConfig
การทดสอบต้องใช้ tfmot.quantization.keras.QuantizeConfig
ซึ่งอธิบายถึงวิธีการ quantize น้ำหนัก, การเปิดใช้งานและผลของชั้น
ด้านล่างเป็นตัวอย่างที่กำหนดเดียวกัน QuantizeConfig
ใช้สำหรับ Dense
ชั้นในค่าเริ่มต้นของ API
ในช่วงการขยายพันธุ์ไปข้างหน้าในตัวอย่างนี้ LastValueQuantizer
กลับมาใน get_weights_and_quantizers
เรียกว่ามี layer.kernel
เป็น input ผลิตเอาท์พุท แทนที่การส่งออก layer.kernel
ในการขยายพันธุ์ไปข้างหน้าเดิมของ Dense
ชั้นผ่านทางตรรกะที่กำหนดไว้ใน set_quantize_weights
แนวคิดเดียวกันนี้ใช้กับการเปิดใช้งานและเอาต์พุต
LastValueQuantizer = tfmot.quantization.keras.quantizers.LastValueQuantizer
MovingAverageQuantizer = tfmot.quantization.keras.quantizers.MovingAverageQuantizer
class DefaultDenseQuantizeConfig(tfmot.quantization.keras.QuantizeConfig):
# Configure how to quantize weights.
def get_weights_and_quantizers(self, layer):
return [(layer.kernel, LastValueQuantizer(num_bits=8, symmetric=True, narrow_range=False, per_axis=False))]
# Configure how to quantize activations.
def get_activations_and_quantizers(self, layer):
return [(layer.activation, MovingAverageQuantizer(num_bits=8, symmetric=False, narrow_range=False, per_axis=False))]
def set_quantize_weights(self, layer, quantize_weights):
# Add this line for each item returned in `get_weights_and_quantizers`
# , in the same order
layer.kernel = quantize_weights[0]
def set_quantize_activations(self, layer, quantize_activations):
# Add this line for each item returned in `get_activations_and_quantizers`
# , in the same order.
layer.activation = quantize_activations[0]
# Configure how to quantize outputs (may be equivalent to activations).
def get_output_quantizers(self, layer):
return []
def get_config(self):
return {}
หาปริมาณเลเยอร์ Keras ที่กำหนดเอง
ตัวอย่างนี้ใช้ DefaultDenseQuantizeConfig
จะ quantize CustomLayer
การใช้การกำหนดค่าจะเหมือนกันในกรณีการใช้งาน "การทดสอบด้วยการหาปริมาณ"
- สมัคร
tfmot.quantization.keras.quantize_annotate_layer
ไปCustomLayer
และผ่านในQuantizeConfig
- ใช้
tfmot.quantization.keras.quantize_annotate_model
จะยังคง quantize ส่วนที่เหลือของรูปแบบที่มีค่าเริ่มต้นของ API
quantize_annotate_layer = tfmot.quantization.keras.quantize_annotate_layer
quantize_annotate_model = tfmot.quantization.keras.quantize_annotate_model
quantize_scope = tfmot.quantization.keras.quantize_scope
class CustomLayer(tf.keras.layers.Dense):
pass
model = quantize_annotate_model(tf.keras.Sequential([
quantize_annotate_layer(CustomLayer(20, input_shape=(20,)), DefaultDenseQuantizeConfig()),
tf.keras.layers.Flatten()
]))
# `quantize_apply` requires mentioning `DefaultDenseQuantizeConfig` with `quantize_scope`
# as well as the custom Keras layer.
with quantize_scope(
{'DefaultDenseQuantizeConfig': DefaultDenseQuantizeConfig,
'CustomLayer': CustomLayer}):
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(model)
quant_aware_model.summary()
Model: "sequential_8" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_6 (QuantizeL (None, 20) 3 ayer) quant_custom_layer (Quantiz (None, 20) 425 eWrapperV2) quant_flatten_9 (QuantizeWr (None, 20) 1 apperV2) ================================================================= Total params: 429 Trainable params: 420 Non-trainable params: 9 _________________________________________________________________
แก้ไขพารามิเตอร์เชิงปริมาณ
ข้อผิดพลาดทั่วไป: quantizing อคติที่จะน้อยกว่า 32 บิตมักจะเป็นอันตรายต่อความถูกต้องของรูปแบบมากเกินไป
ตัวอย่างนี้ปรับเปลี่ยน Dense
ชั้นที่จะใช้ 4 บิตสำหรับน้ำหนักของมันแทนการเริ่มต้น 8 บิต โมเดลที่เหลือยังคงใช้ค่าเริ่มต้นของ API
quantize_annotate_layer = tfmot.quantization.keras.quantize_annotate_layer
quantize_annotate_model = tfmot.quantization.keras.quantize_annotate_model
quantize_scope = tfmot.quantization.keras.quantize_scope
class ModifiedDenseQuantizeConfig(DefaultDenseQuantizeConfig):
# Configure weights to quantize with 4-bit instead of 8-bits.
def get_weights_and_quantizers(self, layer):
return [(layer.kernel, LastValueQuantizer(num_bits=4, symmetric=True, narrow_range=False, per_axis=False))]
การใช้การกำหนดค่าจะเหมือนกันในกรณีการใช้งาน "การทดสอบด้วยการหาปริมาณ"
- สมัคร
tfmot.quantization.keras.quantize_annotate_layer
ไปยังDense
ชั้นและผ่านในQuantizeConfig
- ใช้
tfmot.quantization.keras.quantize_annotate_model
จะยังคง quantize ส่วนที่เหลือของรูปแบบที่มีค่าเริ่มต้นของ API
model = quantize_annotate_model(tf.keras.Sequential([
# Pass in modified `QuantizeConfig` to modify this Dense layer.
quantize_annotate_layer(tf.keras.layers.Dense(20, input_shape=(20,)), ModifiedDenseQuantizeConfig()),
tf.keras.layers.Flatten()
]))
# `quantize_apply` requires mentioning `ModifiedDenseQuantizeConfig` with `quantize_scope`:
with quantize_scope(
{'ModifiedDenseQuantizeConfig': ModifiedDenseQuantizeConfig}):
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(model)
quant_aware_model.summary()
Model: "sequential_9" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_7 (QuantizeL (None, 20) 3 ayer) quant_dense_9 (QuantizeWrap (None, 20) 425 perV2) quant_flatten_10 (QuantizeW (None, 20) 1 rapperV2) ================================================================= Total params: 429 Trainable params: 420 Non-trainable params: 9 _________________________________________________________________
แก้ไขส่วนของเลเยอร์เพื่อกำหนดปริมาณ
ตัวอย่างนี้ปรับเปลี่ยน Dense
ชั้นเพื่อข้าม quantizing การเปิดใช้งาน โมเดลที่เหลือยังคงใช้ค่าเริ่มต้นของ API
quantize_annotate_layer = tfmot.quantization.keras.quantize_annotate_layer
quantize_annotate_model = tfmot.quantization.keras.quantize_annotate_model
quantize_scope = tfmot.quantization.keras.quantize_scope
class ModifiedDenseQuantizeConfig(DefaultDenseQuantizeConfig):
def get_activations_and_quantizers(self, layer):
# Skip quantizing activations.
return []
def set_quantize_activations(self, layer, quantize_activations):
# Empty since `get_activaations_and_quantizers` returns
# an empty list.
return
การใช้การกำหนดค่าจะเหมือนกันในกรณีการใช้งาน "การทดสอบด้วยการหาปริมาณ"
- สมัคร
tfmot.quantization.keras.quantize_annotate_layer
ไปยังDense
ชั้นและผ่านในQuantizeConfig
- ใช้
tfmot.quantization.keras.quantize_annotate_model
จะยังคง quantize ส่วนที่เหลือของรูปแบบที่มีค่าเริ่มต้นของ API
model = quantize_annotate_model(tf.keras.Sequential([
# Pass in modified `QuantizeConfig` to modify this Dense layer.
quantize_annotate_layer(tf.keras.layers.Dense(20, input_shape=(20,)), ModifiedDenseQuantizeConfig()),
tf.keras.layers.Flatten()
]))
# `quantize_apply` requires mentioning `ModifiedDenseQuantizeConfig` with `quantize_scope`:
with quantize_scope(
{'ModifiedDenseQuantizeConfig': ModifiedDenseQuantizeConfig}):
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(model)
quant_aware_model.summary()
Model: "sequential_10" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_8 (QuantizeL (None, 20) 3 ayer) quant_dense_10 (QuantizeWra (None, 20) 423 pperV2) quant_flatten_11 (QuantizeW (None, 20) 1 rapperV2) ================================================================= Total params: 427 Trainable params: 420 Non-trainable params: 7 _________________________________________________________________
ใช้อัลกอริธึมการหาปริมาณแบบกำหนดเอง
tfmot.quantization.keras.quantizers.Quantizer
ชั้น callable ที่สามารถใช้ขั้นตอนวิธีการใด ๆ เพื่อให้ปัจจัยการผลิตของตน
ในตัวอย่างนี้ปัจจัยการผลิตที่มีน้ำหนักและเราใช้คณิตศาสตร์ใน FixedRangeQuantizer
ฟังก์ชั่นการ __call__ น้ำหนัก แทนค่าน้ำหนักเดิมเอาท์พุทของ FixedRangeQuantizer
ถูกส่งผ่านไปตอนนี้สิ่งที่จะได้ใช้น้ำหนัก
quantize_annotate_layer = tfmot.quantization.keras.quantize_annotate_layer
quantize_annotate_model = tfmot.quantization.keras.quantize_annotate_model
quantize_scope = tfmot.quantization.keras.quantize_scope
class FixedRangeQuantizer(tfmot.quantization.keras.quantizers.Quantizer):
"""Quantizer which forces outputs to be between -1 and 1."""
def build(self, tensor_shape, name, layer):
# Not needed. No new TensorFlow variables needed.
return {}
def __call__(self, inputs, training, weights, **kwargs):
return tf.keras.backend.clip(inputs, -1.0, 1.0)
def get_config(self):
# Not needed. No __init__ parameters to serialize.
return {}
class ModifiedDenseQuantizeConfig(DefaultDenseQuantizeConfig):
# Configure weights to quantize with 4-bit instead of 8-bits.
def get_weights_and_quantizers(self, layer):
# Use custom algorithm defined in `FixedRangeQuantizer` instead of default Quantizer.
return [(layer.kernel, FixedRangeQuantizer())]
การใช้การกำหนดค่าจะเหมือนกันในกรณีการใช้งาน "การทดสอบด้วยการหาปริมาณ"
- สมัคร
tfmot.quantization.keras.quantize_annotate_layer
ไปยังDense
ชั้นและผ่านในQuantizeConfig
- ใช้
tfmot.quantization.keras.quantize_annotate_model
จะยังคง quantize ส่วนที่เหลือของรูปแบบที่มีค่าเริ่มต้นของ API
model = quantize_annotate_model(tf.keras.Sequential([
# Pass in modified `QuantizeConfig` to modify this `Dense` layer.
quantize_annotate_layer(tf.keras.layers.Dense(20, input_shape=(20,)), ModifiedDenseQuantizeConfig()),
tf.keras.layers.Flatten()
]))
# `quantize_apply` requires mentioning `ModifiedDenseQuantizeConfig` with `quantize_scope`:
with quantize_scope(
{'ModifiedDenseQuantizeConfig': ModifiedDenseQuantizeConfig}):
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(model)
quant_aware_model.summary()
Model: "sequential_11" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= quantize_layer_9 (QuantizeL (None, 20) 3 ayer) quant_dense_11 (QuantizeWra (None, 20) 423 pperV2) quant_flatten_12 (QuantizeW (None, 20) 1 rapperV2) ================================================================= Total params: 427 Trainable params: 420 Non-trainable params: 7 _________________________________________________________________