mirror of
https://github.com/PaddlePaddle/PaddleOCR.git
synced 2026-11-25 17:29:39 +08:00
feat: add PP-OCRv6 detection and recognition modules (#18116)
This commit is contained in:
37 files changed
+3891
-77
No files matched your search
@@ -0,0 +1,195 @@
|
||||
Global:
|
||||
model_name: PP-OCRv6_medium_det # To use static model for inference.
|
||||
debug: false
|
||||
use_gpu: true
|
||||
use_ema: true
|
||||
ema_decay: 0.9996
|
||||
ema_decay_type: threshold
|
||||
epoch_num: &epoch_num 500
|
||||
log_smooth_window: 20
|
||||
print_batch_step: 10
|
||||
save_model_dir: ./output/PP-OCRv6_medium_det
|
||||
save_epoch_step: 10
|
||||
eval_batch_step:
|
||||
- 0
|
||||
- 1500
|
||||
cal_metric_during_train: false
|
||||
checkpoints: null
|
||||
pretrained_model: null
|
||||
save_inference_dir: null
|
||||
use_visualdl: false
|
||||
infer_img: doc/imgs_en/img_10.jpg
|
||||
save_res_path: ./checkpoints/det_db/predicts_db.txt
|
||||
d2s_train_image_shape: [3, 640, 640]
|
||||
distributed: true
|
||||
|
||||
Architecture:
|
||||
model_type: det
|
||||
algorithm: DB
|
||||
Transform: null
|
||||
Backbone:
|
||||
name: PPLCNetV4
|
||||
det: true
|
||||
model_size: medium
|
||||
Neck:
|
||||
name: RepLKPAN
|
||||
out_channels: 256
|
||||
intracl: true
|
||||
Head:
|
||||
name: DBHead
|
||||
k: 50
|
||||
fix_nan: true
|
||||
aux_in_channels: 256
|
||||
|
||||
Loss:
|
||||
name: DBLoss
|
||||
main_loss_type: DiceFocalLoss
|
||||
alpha: 5
|
||||
beta: 10
|
||||
focal_alpha: 0.25
|
||||
focal_gamma: 2.5
|
||||
aux_weight_p4: 0.2
|
||||
aux_weight_p3: 0.3
|
||||
aux_weight_p2: 0.4
|
||||
|
||||
Optimizer:
|
||||
name: Adam
|
||||
beta1: 0.9
|
||||
beta2: 0.999
|
||||
lr:
|
||||
name: Cosine
|
||||
learning_rate: 0.001 #(8*8c)
|
||||
warmup_epoch: 2
|
||||
regularizer:
|
||||
name: L2
|
||||
factor: 1.0e-05
|
||||
|
||||
PostProcess:
|
||||
name: DBPostProcess
|
||||
thresh: 0.2
|
||||
box_thresh: 0.45
|
||||
max_candidates: 3000
|
||||
unclip_ratio: 1.4
|
||||
|
||||
Metric:
|
||||
name: DetMetric
|
||||
main_indicator: hmean
|
||||
|
||||
Train:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data/icdar2015/text_localization/
|
||||
label_file_list:
|
||||
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
|
||||
ratio_list: [1.0]
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- DetLabelEncode: null
|
||||
- CopyPaste: null
|
||||
- ColorJitter:
|
||||
brightness: 0.4
|
||||
contrast: 0.4
|
||||
saturation: 0.7
|
||||
hue: 0.1
|
||||
- IaaAugment:
|
||||
augmenter_args:
|
||||
- type: Fliplr
|
||||
args:
|
||||
p: 0.5
|
||||
- type: Affine
|
||||
args:
|
||||
p: 0.5
|
||||
rotate:
|
||||
- -45
|
||||
- 45
|
||||
fit_output: true
|
||||
- type: Resize
|
||||
args:
|
||||
size:
|
||||
- 0.1
|
||||
- 2
|
||||
- RandomPerspective:
|
||||
prob: 0.3
|
||||
scale: 0.0
|
||||
shear: 20.0
|
||||
perspective: 0.001
|
||||
fit_output: true
|
||||
fill_value: [0, 0, 0]
|
||||
- RandomCrop:
|
||||
size:
|
||||
- 640
|
||||
- 640
|
||||
max_tries: 50
|
||||
keep_ratio: true
|
||||
- MakeBorderMap:
|
||||
shrink_ratio: 0.4
|
||||
thresh_min: 0.3
|
||||
thresh_max: 0.7
|
||||
total_epoch: *epoch_num
|
||||
- MakeShrinkMap:
|
||||
shrink_ratio: 0.4
|
||||
min_text_size: 8
|
||||
total_epoch: *epoch_num
|
||||
- NormalizeImage:
|
||||
scale: 1./255.
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
order: hwc
|
||||
- ToCHWImage: null
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- threshold_map
|
||||
- threshold_mask
|
||||
- shrink_map
|
||||
- shrink_mask
|
||||
loader:
|
||||
shuffle: true
|
||||
drop_last: false
|
||||
batch_size_per_card: 8
|
||||
num_workers: 8
|
||||
|
||||
Eval:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data/icdar2015/text_localization/
|
||||
label_file_list:
|
||||
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- DetLabelEncode: null
|
||||
- DetResizeForTest: null
|
||||
- NormalizeImage:
|
||||
scale: 1./255.
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
order: hwc
|
||||
- ToCHWImage: null
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- shape
|
||||
- polys
|
||||
- ignore_tags
|
||||
loader:
|
||||
shuffle: false
|
||||
drop_last: false
|
||||
batch_size_per_card: 1
|
||||
num_workers: 2
|
||||
profiler_options: null
|
||||
@@ -0,0 +1,184 @@
|
||||
Global:
|
||||
model_name: PP-OCRv6_small_det # To use static model for inference.
|
||||
debug: false
|
||||
use_gpu: true
|
||||
use_ema: true
|
||||
ema_decay: 0.9997
|
||||
ema_decay_type: threshold
|
||||
epoch_num: &epoch_num 500
|
||||
log_smooth_window: 20
|
||||
print_batch_step: 10
|
||||
save_model_dir: ./output/PP-OCRv6_small_det
|
||||
save_epoch_step: 10
|
||||
eval_batch_step:
|
||||
- 0
|
||||
- 1500
|
||||
cal_metric_during_train: false
|
||||
checkpoints: null
|
||||
pretrained_model: null
|
||||
save_inference_dir: null
|
||||
use_visualdl: false
|
||||
infer_img: doc/imgs_en/img_10.jpg
|
||||
save_res_path: ./checkpoints/det_db/predicts_db.txt
|
||||
d2s_train_image_shape: [3, 640, 640]
|
||||
distributed: true
|
||||
|
||||
Architecture:
|
||||
model_type: det
|
||||
algorithm: DB
|
||||
Transform: null
|
||||
Backbone:
|
||||
name: PPLCNetV4
|
||||
det: true
|
||||
model_size: small
|
||||
Neck:
|
||||
name: RepLKFPN
|
||||
out_channels: 96
|
||||
dilated_kernel_size: 7
|
||||
shortcut: true
|
||||
Head:
|
||||
name: DBHead
|
||||
k: 50
|
||||
fix_nan: true
|
||||
aux_in_channels: 96
|
||||
|
||||
Loss:
|
||||
name: DBLoss
|
||||
main_loss_type: DiceFocalLoss
|
||||
alpha: 5
|
||||
beta: 10
|
||||
focal_alpha: 0.25
|
||||
focal_gamma: 2.5
|
||||
aux_weight_p4: 0.2
|
||||
aux_weight_p3: 0.3
|
||||
aux_weight_p2: 0.4
|
||||
|
||||
Optimizer:
|
||||
name: Adam
|
||||
beta1: 0.9
|
||||
beta2: 0.999
|
||||
lr:
|
||||
name: Cosine
|
||||
learning_rate: 0.001 #(8*8c)
|
||||
warmup_epoch: 2
|
||||
regularizer:
|
||||
name: L2
|
||||
factor: 1.0e-05
|
||||
|
||||
PostProcess:
|
||||
name: DBPostProcess
|
||||
thresh: 0.2
|
||||
box_thresh: 0.45
|
||||
max_candidates: 3000
|
||||
unclip_ratio: 1.4
|
||||
|
||||
Metric:
|
||||
name: DetMetric
|
||||
main_indicator: hmean
|
||||
|
||||
Train:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data/icdar2015/text_localization/
|
||||
label_file_list:
|
||||
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
|
||||
ratio_list: [1.0]
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- DetLabelEncode: null
|
||||
- CopyPaste: null
|
||||
- IaaAugment:
|
||||
augmenter_args:
|
||||
- type: Fliplr
|
||||
args:
|
||||
p: 0.5
|
||||
- type: Affine
|
||||
args:
|
||||
p: 0.5
|
||||
rotate:
|
||||
- -45
|
||||
- 45
|
||||
fit_output: true
|
||||
- type: Resize
|
||||
args:
|
||||
size:
|
||||
- 0.1
|
||||
- 2
|
||||
- RandomCrop:
|
||||
size:
|
||||
- 640
|
||||
- 640
|
||||
max_tries: 50
|
||||
keep_ratio: true
|
||||
- MakeBorderMap:
|
||||
shrink_ratio: 0.4
|
||||
thresh_min: 0.3
|
||||
thresh_max: 0.7
|
||||
total_epoch: *epoch_num
|
||||
- MakeShrinkMap:
|
||||
shrink_ratio: 0.4
|
||||
min_text_size: 8
|
||||
total_epoch: *epoch_num
|
||||
- NormalizeImage:
|
||||
scale: 1./255.
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
order: hwc
|
||||
- ToCHWImage: null
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- threshold_map
|
||||
- threshold_mask
|
||||
- shrink_map
|
||||
- shrink_mask
|
||||
loader:
|
||||
shuffle: true
|
||||
drop_last: false
|
||||
batch_size_per_card: 8
|
||||
num_workers: 8
|
||||
|
||||
Eval:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data/icdar2015/text_localization/
|
||||
label_file_list:
|
||||
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- DetLabelEncode: null
|
||||
- DetResizeForTest: null
|
||||
- NormalizeImage:
|
||||
scale: 1./255.
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
order: hwc
|
||||
- ToCHWImage: null
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- shape
|
||||
- polys
|
||||
- ignore_tags
|
||||
loader:
|
||||
shuffle: false
|
||||
drop_last: false
|
||||
batch_size_per_card: 1
|
||||
num_workers: 2
|
||||
profiler_options: null
|
||||
@@ -0,0 +1,189 @@
|
||||
Global:
|
||||
model_name: PP-OCRv6_tiny_det # To use static model for inference.
|
||||
debug: false
|
||||
use_gpu: true
|
||||
use_ema: true
|
||||
ema_decay: 0.9998
|
||||
ema_decay_type: threshold
|
||||
epoch_num: &epoch_num 500
|
||||
log_smooth_window: 20
|
||||
print_batch_step: 10
|
||||
save_model_dir: ./output/PP-OCRv6_tiny_det
|
||||
save_epoch_step: 10
|
||||
eval_batch_step:
|
||||
- 0
|
||||
- 1500
|
||||
cal_metric_during_train: false
|
||||
checkpoints: null
|
||||
pretrained_model: null
|
||||
save_inference_dir: null
|
||||
use_visualdl: false
|
||||
infer_img: doc/imgs_en/img_10.jpg
|
||||
save_res_path: ./checkpoints/det_db/predicts_db.txt
|
||||
d2s_train_image_shape: [3, 640, 640]
|
||||
distributed: true
|
||||
|
||||
Architecture:
|
||||
model_type: det
|
||||
algorithm: DB
|
||||
Transform: null
|
||||
Backbone:
|
||||
name: PPLCNetV4
|
||||
det: true
|
||||
model_size: tiny
|
||||
Neck:
|
||||
name: RepLKFPN
|
||||
out_channels: 64
|
||||
dilated_kernel_size: 5
|
||||
shortcut: true
|
||||
Head:
|
||||
name: DBHead
|
||||
k: 50
|
||||
fix_nan: true
|
||||
aux_in_channels: 64
|
||||
|
||||
Loss:
|
||||
name: DBLoss
|
||||
main_loss_type: DiceFocalLoss
|
||||
alpha: 5
|
||||
beta: 10
|
||||
focal_alpha: 0.25
|
||||
focal_gamma: 2.5
|
||||
aux_weight_p4: 0.2
|
||||
aux_weight_p3: 0.3
|
||||
aux_weight_p2: 0.4
|
||||
|
||||
Optimizer:
|
||||
name: Adam
|
||||
beta1: 0.9
|
||||
beta2: 0.999
|
||||
lr:
|
||||
name: Cosine
|
||||
learning_rate: 0.001 #(8*8c)
|
||||
warmup_epoch: 2
|
||||
regularizer:
|
||||
name: L2
|
||||
factor: 1.0e-06
|
||||
|
||||
PostProcess:
|
||||
name: DBPostProcess
|
||||
thresh: 0.2
|
||||
box_thresh: 0.4
|
||||
max_candidates: 3000
|
||||
unclip_ratio: 1.4
|
||||
|
||||
Metric:
|
||||
name: DetMetric
|
||||
main_indicator: hmean
|
||||
|
||||
Train:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data/icdar2015/text_localization/
|
||||
label_file_list:
|
||||
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
|
||||
ratio_list: [1.0]
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- DetLabelEncode: null
|
||||
- CopyPaste: null
|
||||
- ColorJitter:
|
||||
brightness: 0.4
|
||||
contrast: 0.4
|
||||
saturation: 0.7
|
||||
hue: 0.1
|
||||
- IaaAugment:
|
||||
augmenter_args:
|
||||
- type: Fliplr
|
||||
args:
|
||||
p: 0.5
|
||||
- type: Affine
|
||||
args:
|
||||
p: 0.5
|
||||
rotate:
|
||||
- -45
|
||||
- 45
|
||||
fit_output: true
|
||||
- type: Resize
|
||||
args:
|
||||
size:
|
||||
- 0.3
|
||||
- 2
|
||||
- RandomCrop:
|
||||
size:
|
||||
- 640
|
||||
- 640
|
||||
max_tries: 50
|
||||
keep_ratio: true
|
||||
- MakeBorderMap:
|
||||
shrink_ratio: 0.4
|
||||
thresh_min: 0.3
|
||||
thresh_max: 0.7
|
||||
total_epoch: *epoch_num
|
||||
- MakeShrinkMap:
|
||||
shrink_ratio: 0.4
|
||||
min_text_size: 8
|
||||
total_epoch: *epoch_num
|
||||
- NormalizeImage:
|
||||
scale: 1./255.
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
order: hwc
|
||||
- ToCHWImage: null
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- threshold_map
|
||||
- threshold_mask
|
||||
- shrink_map
|
||||
- shrink_mask
|
||||
loader:
|
||||
shuffle: true
|
||||
drop_last: false
|
||||
batch_size_per_card: 8
|
||||
num_workers: 8
|
||||
|
||||
Eval:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data/icdar2015/text_localization/
|
||||
label_file_list:
|
||||
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- DetLabelEncode: null
|
||||
- DetResizeForTest: null
|
||||
- NormalizeImage:
|
||||
scale: 1./255.
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
order: hwc
|
||||
- ToCHWImage: null
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- shape
|
||||
- polys
|
||||
- ignore_tags
|
||||
loader:
|
||||
shuffle: false
|
||||
drop_last: false
|
||||
batch_size_per_card: 1
|
||||
num_workers: 2
|
||||
profiler_options: null
|
||||
@@ -0,0 +1,143 @@
|
||||
Global:
|
||||
model_name: PP-OCRv6_base_rec
|
||||
debug: false
|
||||
use_gpu: true
|
||||
epoch_num: 100
|
||||
log_smooth_window: 20
|
||||
print_batch_step: 10
|
||||
save_model_dir: ./output/PP-OCRv6_base_rec
|
||||
save_epoch_step: 10
|
||||
eval_batch_step: [0, 2000]
|
||||
cal_metric_during_train: true
|
||||
pretrained_model:
|
||||
checkpoints:
|
||||
save_inference_dir:
|
||||
use_visualdl: false
|
||||
infer_img: doc/imgs_words/ch/word_1.jpg
|
||||
character_dict_path: ppocr/utils/dict/ppocrv5_dict.txt
|
||||
max_text_length: &max_text_length 25
|
||||
infer_mode: false
|
||||
use_space_char: true
|
||||
distributed: true
|
||||
save_res_path: ./output/rec/predicts_ppocrv6_base.txt
|
||||
d2s_train_image_shape: [3, 48, 320]
|
||||
|
||||
|
||||
Optimizer:
|
||||
name: Adam
|
||||
beta1: 0.9
|
||||
beta2: 0.999
|
||||
lr:
|
||||
name: Cosine
|
||||
learning_rate: 0.0005
|
||||
warmup_epoch: 5
|
||||
regularizer:
|
||||
name: L2
|
||||
factor: 3.0e-05
|
||||
|
||||
|
||||
Architecture:
|
||||
model_type: rec
|
||||
algorithm: SVTR_LCNet
|
||||
Transform:
|
||||
Backbone:
|
||||
name: PPLCNetV4
|
||||
model_size: base
|
||||
Head:
|
||||
name: MultiHead
|
||||
head_list:
|
||||
- CTCHead:
|
||||
Neck:
|
||||
name: lightsvtr
|
||||
dims: 192
|
||||
depth: 3
|
||||
mlp_ratio: 4.0
|
||||
local_kernel: 7
|
||||
use_guide: true
|
||||
Head:
|
||||
fc_decay: 0.00001
|
||||
- NRTRHead:
|
||||
nrtr_dim: 384
|
||||
max_text_length: *max_text_length
|
||||
|
||||
Loss:
|
||||
name: MultiLoss
|
||||
loss_config_list:
|
||||
- CTCLoss:
|
||||
- NRTRLoss:
|
||||
|
||||
PostProcess:
|
||||
name: CTCLabelDecode
|
||||
|
||||
Metric:
|
||||
name: RecMetric
|
||||
main_indicator: acc
|
||||
|
||||
Train:
|
||||
dataset:
|
||||
name: MultiScaleDataSet
|
||||
ds_width: false
|
||||
data_dir: ./train_data/
|
||||
ext_op_transform_idx: 1
|
||||
label_file_list:
|
||||
- ./train_data/train_list.txt
|
||||
ratio_list:
|
||||
- 0.5
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- RecConAug:
|
||||
prob: 0.5
|
||||
ext_data_num: 2
|
||||
image_shape: [48, 320, 3]
|
||||
max_text_length: *max_text_length
|
||||
- RecAug:
|
||||
- MultiLabelEncode:
|
||||
gtc_encode: NRTRLabelEncode
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- label_ctc
|
||||
- label_gtc
|
||||
- length
|
||||
- valid_ratio
|
||||
sampler:
|
||||
name: MultiScaleSampler
|
||||
scales: [[320, 32], [320, 48], [320, 64]]
|
||||
first_bs: &bs 64
|
||||
fix_bs: false
|
||||
divided_factor: [8, 16]
|
||||
is_training: True
|
||||
loader:
|
||||
shuffle: true
|
||||
batch_size_per_card: *bs
|
||||
drop_last: true
|
||||
num_workers: 8
|
||||
|
||||
Eval:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data
|
||||
label_file_list:
|
||||
- ./train_data/val_list.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- MultiLabelEncode:
|
||||
gtc_encode: NRTRLabelEncode
|
||||
- RecResizeImg:
|
||||
image_shape: [3, 48, 320]
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- label_ctc
|
||||
- label_gtc
|
||||
- length
|
||||
- valid_ratio
|
||||
loader:
|
||||
shuffle: false
|
||||
drop_last: false
|
||||
batch_size_per_card: 128
|
||||
num_workers: 4
|
||||
@@ -0,0 +1,140 @@
|
||||
Global:
|
||||
model_name: PP-OCRv6_small_rec
|
||||
debug: false
|
||||
use_gpu: true
|
||||
epoch_num: 100
|
||||
log_smooth_window: 20
|
||||
print_batch_step: 10
|
||||
save_model_dir: ./output/PP-OCRv6_small_rec
|
||||
save_epoch_step: 10
|
||||
eval_batch_step: [0, 2000]
|
||||
cal_metric_during_train: true
|
||||
pretrained_model:
|
||||
checkpoints:
|
||||
save_inference_dir:
|
||||
use_visualdl: false
|
||||
infer_img: doc/imgs_words/ch/word_1.jpg
|
||||
character_dict_path: ppocr/utils/dict/ppocrv5_dict.txt
|
||||
max_text_length: &max_text_length 25
|
||||
infer_mode: false
|
||||
use_space_char: true
|
||||
distributed: true
|
||||
save_res_path: ./output/rec/predicts_ppocrv6_small.txt
|
||||
d2s_train_image_shape: [3, 48, 320]
|
||||
|
||||
|
||||
Optimizer:
|
||||
name: Adam
|
||||
beta1: 0.9
|
||||
beta2: 0.999
|
||||
lr:
|
||||
name: Cosine
|
||||
learning_rate: 0.0005
|
||||
warmup_epoch: 5
|
||||
regularizer:
|
||||
name: L2
|
||||
factor: 3.0e-05
|
||||
|
||||
|
||||
Architecture:
|
||||
model_type: rec
|
||||
algorithm: SVTR_LCNet
|
||||
Transform:
|
||||
Backbone:
|
||||
name: PPLCNetV4
|
||||
model_size: small
|
||||
Head:
|
||||
name: MultiHead
|
||||
head_list:
|
||||
- CTCHead:
|
||||
Neck:
|
||||
name: lightsvtr
|
||||
dims: 120
|
||||
depth: 2
|
||||
mlp_ratio: 2.0
|
||||
local_kernel: 7
|
||||
Head:
|
||||
fc_decay: 0.00001
|
||||
- NRTRHead:
|
||||
nrtr_dim: 384
|
||||
max_text_length: *max_text_length
|
||||
|
||||
Loss:
|
||||
name: MultiLoss
|
||||
loss_config_list:
|
||||
- CTCLoss:
|
||||
- NRTRLoss:
|
||||
|
||||
PostProcess:
|
||||
name: CTCLabelDecode
|
||||
|
||||
Metric:
|
||||
name: RecMetric
|
||||
main_indicator: acc
|
||||
|
||||
Train:
|
||||
dataset:
|
||||
name: MultiScaleDataSet
|
||||
ds_width: false
|
||||
data_dir: ./train_data/
|
||||
ext_op_transform_idx: 1
|
||||
label_file_list:
|
||||
- ./train_data/train_list.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- RecConAug:
|
||||
prob: 0.5
|
||||
ext_data_num: 2
|
||||
image_shape: [48, 320, 3]
|
||||
max_text_length: *max_text_length
|
||||
- RecAug:
|
||||
- MultiLabelEncode:
|
||||
gtc_encode: NRTRLabelEncode
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- label_ctc
|
||||
- label_gtc
|
||||
- length
|
||||
- valid_ratio
|
||||
sampler:
|
||||
name: MultiScaleSampler
|
||||
scales: [[320, 32], [320, 48], [320, 64]]
|
||||
first_bs: &bs 128
|
||||
fix_bs: false
|
||||
divided_factor: [8, 16]
|
||||
is_training: True
|
||||
loader:
|
||||
shuffle: true
|
||||
batch_size_per_card: *bs
|
||||
drop_last: true
|
||||
num_workers: 8
|
||||
|
||||
Eval:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data
|
||||
label_file_list:
|
||||
- ./train_data/val_list.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- MultiLabelEncode:
|
||||
gtc_encode: NRTRLabelEncode
|
||||
- RecResizeImg:
|
||||
image_shape: [3, 48, 320]
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- label_ctc
|
||||
- label_gtc
|
||||
- length
|
||||
- valid_ratio
|
||||
loader:
|
||||
shuffle: false
|
||||
drop_last: false
|
||||
batch_size_per_card: 128
|
||||
num_workers: 4
|
||||
@@ -0,0 +1,138 @@
|
||||
Global:
|
||||
model_name: PP-OCRv6_tiny_rec
|
||||
debug: false
|
||||
use_gpu: true
|
||||
epoch_num: 100
|
||||
log_smooth_window: 20
|
||||
print_batch_step: 10
|
||||
save_model_dir: ./output/PP-OCRv6_tiny_rec
|
||||
save_epoch_step: 10
|
||||
eval_batch_step: [0, 2000]
|
||||
cal_metric_during_train: true
|
||||
pretrained_model:
|
||||
checkpoints:
|
||||
save_inference_dir:
|
||||
use_visualdl: false
|
||||
infer_img: doc/imgs_words/ch/word_1.jpg
|
||||
character_dict_path: ppocr/utils/ppocr_keys_v1.txt
|
||||
max_text_length: &max_text_length 25
|
||||
infer_mode: false
|
||||
use_space_char: true
|
||||
distributed: true
|
||||
save_res_path: ./output/rec/predicts_ppocrv6_tiny.txt
|
||||
d2s_train_image_shape: [3, 48, 320]
|
||||
|
||||
|
||||
Optimizer:
|
||||
name: Adam
|
||||
beta1: 0.9
|
||||
beta2: 0.999
|
||||
lr:
|
||||
name: Cosine
|
||||
learning_rate: 0.001
|
||||
warmup_epoch: 5
|
||||
regularizer:
|
||||
name: L2
|
||||
factor: 3.0e-05
|
||||
|
||||
|
||||
Architecture:
|
||||
model_type: rec
|
||||
algorithm: SVTR_LCNet
|
||||
Transform:
|
||||
Backbone:
|
||||
name: PPLCNetV4
|
||||
model_size: tiny
|
||||
Head:
|
||||
name: MultiHead
|
||||
head_list:
|
||||
- CTCHead:
|
||||
Neck:
|
||||
name: reshape
|
||||
Head:
|
||||
mid_channels: 80
|
||||
use_guide: true
|
||||
fc_decay: 0.00001
|
||||
- NRTRHead:
|
||||
nrtr_dim: 384
|
||||
max_text_length: *max_text_length
|
||||
|
||||
Loss:
|
||||
name: MultiLoss
|
||||
loss_config_list:
|
||||
- CTCLoss:
|
||||
- NRTRLoss:
|
||||
|
||||
PostProcess:
|
||||
name: CTCLabelDecode
|
||||
|
||||
Metric:
|
||||
name: RecMetric
|
||||
main_indicator: acc
|
||||
|
||||
Train:
|
||||
dataset:
|
||||
name: MultiScaleDataSet
|
||||
ds_width: false
|
||||
data_dir: ./train_data/
|
||||
ext_op_transform_idx: 1
|
||||
label_file_list:
|
||||
- ./train_data/train_list.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- RecConAug:
|
||||
prob: 0.5
|
||||
ext_data_num: 2
|
||||
image_shape: [48, 320, 3]
|
||||
max_text_length: *max_text_length
|
||||
- RecAug:
|
||||
- MultiLabelEncode:
|
||||
gtc_encode: NRTRLabelEncode
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- label_ctc
|
||||
- label_gtc
|
||||
- length
|
||||
- valid_ratio
|
||||
sampler:
|
||||
name: MultiScaleSampler
|
||||
scales: [[320, 32], [320, 48], [320, 64]]
|
||||
first_bs: &bs 128
|
||||
fix_bs: false
|
||||
divided_factor: [8, 16]
|
||||
is_training: True
|
||||
loader:
|
||||
shuffle: true
|
||||
batch_size_per_card: *bs
|
||||
drop_last: true
|
||||
num_workers: 8
|
||||
|
||||
Eval:
|
||||
dataset:
|
||||
name: SimpleDataSet
|
||||
data_dir: ./train_data
|
||||
label_file_list:
|
||||
- ./train_data/val_list.txt
|
||||
transforms:
|
||||
- DecodeImage:
|
||||
img_mode: BGR
|
||||
channel_first: false
|
||||
- MultiLabelEncode:
|
||||
gtc_encode: NRTRLabelEncode
|
||||
- RecResizeImg:
|
||||
image_shape: [3, 48, 320]
|
||||
- KeepKeys:
|
||||
keep_keys:
|
||||
- image
|
||||
- label_ctc
|
||||
- label_gtc
|
||||
- length
|
||||
- valid_ratio
|
||||
loader:
|
||||
shuffle: false
|
||||
drop_last: false
|
||||
batch_size_per_card: 128
|
||||
num_workers: 8
|
||||
@@ -95,7 +95,7 @@ def main(config, device, logger, vdl_writer):
|
||||
loss_class = build_loss(config["Loss"])
|
||||
|
||||
# build optim
|
||||
optimizer, lr_scheduler = build_optimizer(
|
||||
optimizer, lr_scheduler, _wd_scheduler = build_optimizer(
|
||||
config["Optimizer"],
|
||||
epochs=config["Global"]["epoch_num"],
|
||||
step_each_epoch=len(train_dataloader),
|
||||
|
||||
@@ -182,7 +182,7 @@ def main(config, device, logger, vdl_writer):
|
||||
loss_class = build_loss(config["Loss"])
|
||||
|
||||
# build optim
|
||||
optimizer, lr_scheduler = build_optimizer(
|
||||
optimizer, lr_scheduler, _wd_scheduler = build_optimizer(
|
||||
config["Optimizer"],
|
||||
epochs=config["Global"]["epoch_num"],
|
||||
step_each_epoch=len(train_dataloader),
|
||||
|
||||
@@ -148,6 +148,7 @@ def build_dataloader(config, mode, device, logger, seed=None):
|
||||
return_list=True,
|
||||
use_shared_memory=use_shared_memory,
|
||||
collate_fn=collate_fn,
|
||||
persistent_workers=True if num_workers > 0 and mode == "Train" else False,
|
||||
)
|
||||
|
||||
return data_loader
|
||||
@@ -19,7 +19,7 @@ from __future__ import unicode_literals
|
||||
from .iaa_augment import IaaAugment
|
||||
from .make_border_map import MakeBorderMap
|
||||
from .make_shrink_map import MakeShrinkMap
|
||||
from .random_crop_data import EastRandomCropData, RandomCropImgMask
|
||||
from .random_crop_data import EastRandomCropData, RandomCrop, RandomCropImgMask
|
||||
from .make_pse_gt import MakePseGt
|
||||
|
||||
|
||||
|
||||
@@ -156,7 +156,14 @@ class AugmenterBuilder(object):
|
||||
elif isinstance(rotate, (int, float)):
|
||||
rotate = (float(rotate), float(rotate))
|
||||
augmenter_args["rotate"] = rotate
|
||||
augmenter_args["p"] = 1.0
|
||||
augmenter_args["p"] = augmenter_args.get("p", 1.0)
|
||||
if augmenter_args.get("fit_output") is True:
|
||||
if "border_mode" not in augmenter_args:
|
||||
import cv2
|
||||
|
||||
augmenter_args["border_mode"] = cv2.BORDER_CONSTANT
|
||||
if "fill" not in augmenter_args:
|
||||
augmenter_args["fill"] = 0
|
||||
return augmenter_args
|
||||
else:
|
||||
# For other augmenters, ensure 'p' probability is specified
|
||||
|
||||
@@ -70,6 +70,10 @@ class DetLabelEncode(object):
|
||||
boxes = np.array(boxes, dtype=np.float32)
|
||||
txt_tags = np.array(txt_tags, dtype=np.bool_)
|
||||
|
||||
# Mark polygons with NaN coordinates as ignore to avoid downstream errors
|
||||
nan_mask = np.isnan(boxes).any(axis=(1, 2))
|
||||
txt_tags[nan_mask] = True
|
||||
|
||||
data["polys"] = boxes
|
||||
data["texts"] = txts
|
||||
data["ignore_tags"] = txt_tags
|
||||
|
||||
@@ -40,47 +40,59 @@ class MakeBorderMap(object):
|
||||
self.shrink_ratio = shrink_ratio
|
||||
self.thresh_min = thresh_min
|
||||
self.thresh_max = thresh_max
|
||||
if "total_epoch" in kwargs and "epoch" in kwargs and kwargs["epoch"] != "None":
|
||||
self.shrink_ratio = self.shrink_ratio + 0.2 * kwargs["epoch"] / float(
|
||||
kwargs["total_epoch"]
|
||||
)
|
||||
if "total_epoch" in kwargs:
|
||||
self._base_shrink_ratio = shrink_ratio
|
||||
self._total_epoch = kwargs["total_epoch"]
|
||||
|
||||
def __call__(self, data):
|
||||
img = data["image"]
|
||||
text_polys = data["polys"]
|
||||
ignore_tags = data["ignore_tags"]
|
||||
|
||||
shrink_ratio = self.shrink_ratio
|
||||
if "epoch" in data and hasattr(self, "_base_shrink_ratio"):
|
||||
shrink_ratio = self._base_shrink_ratio + 0.2 * data["epoch"] / float(
|
||||
self._total_epoch
|
||||
)
|
||||
|
||||
canvas = np.zeros(img.shape[:2], dtype=np.float32)
|
||||
mask = np.zeros(img.shape[:2], dtype=np.float32)
|
||||
|
||||
for i in range(len(text_polys)):
|
||||
if ignore_tags[i]:
|
||||
continue
|
||||
self.draw_border_map(text_polys[i], canvas, mask=mask)
|
||||
self.draw_border_map(
|
||||
text_polys[i], canvas, mask=mask, shrink_ratio=shrink_ratio
|
||||
)
|
||||
canvas = canvas * (self.thresh_max - self.thresh_min) + self.thresh_min
|
||||
|
||||
data["threshold_map"] = canvas
|
||||
data["threshold_mask"] = mask
|
||||
return data
|
||||
|
||||
def draw_border_map(self, polygon, canvas, mask):
|
||||
def draw_border_map(self, polygon, canvas, mask, shrink_ratio=None):
|
||||
if shrink_ratio is None:
|
||||
shrink_ratio = self.shrink_ratio
|
||||
polygon = np.array(polygon)
|
||||
assert polygon.ndim == 2
|
||||
assert polygon.shape[1] == 2
|
||||
|
||||
if np.isnan(polygon).any():
|
||||
return
|
||||
polygon_shape = Polygon(polygon)
|
||||
if polygon_shape.area <= 0:
|
||||
return
|
||||
distance = (
|
||||
polygon_shape.area
|
||||
* (1 - np.power(self.shrink_ratio, 2))
|
||||
/ polygon_shape.length
|
||||
polygon_shape.area * (1 - np.power(shrink_ratio, 2)) / polygon_shape.length
|
||||
)
|
||||
subject = [tuple(l) for l in polygon]
|
||||
padding = pyclipper.PyclipperOffset()
|
||||
padding.AddPath(subject, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
|
||||
|
||||
padded_polygon = np.array(padding.Execute(distance)[0])
|
||||
padded_polygon = padding.Execute(distance)
|
||||
if not padded_polygon:
|
||||
return
|
||||
padded_polygon = np.array(padded_polygon[0])
|
||||
cv2.fillPoly(mask, [padded_polygon.astype(np.int32)], 1.0)
|
||||
|
||||
xmin = padded_polygon[:, 0].min()
|
||||
|
||||
@@ -38,10 +38,9 @@ class MakeShrinkMap(object):
|
||||
def __init__(self, min_text_size=8, shrink_ratio=0.4, **kwargs):
|
||||
self.min_text_size = min_text_size
|
||||
self.shrink_ratio = shrink_ratio
|
||||
if "total_epoch" in kwargs and "epoch" in kwargs and kwargs["epoch"] != "None":
|
||||
self.shrink_ratio = self.shrink_ratio + 0.2 * kwargs["epoch"] / float(
|
||||
kwargs["total_epoch"]
|
||||
)
|
||||
if "total_epoch" in kwargs:
|
||||
self._base_shrink_ratio = shrink_ratio
|
||||
self._total_epoch = kwargs["total_epoch"]
|
||||
|
||||
def __call__(self, data):
|
||||
image = data["image"]
|
||||
@@ -60,6 +59,9 @@ class MakeShrinkMap(object):
|
||||
cv2.fillPoly(mask, polygon.astype(np.int32)[np.newaxis, :, :], 0)
|
||||
ignore_tags[i] = True
|
||||
else:
|
||||
if np.isnan(polygon).any():
|
||||
ignore_tags[i] = True
|
||||
continue
|
||||
polygon_shape = Polygon(polygon)
|
||||
subject = [tuple(l) for l in polygon]
|
||||
padding = pyclipper.PyclipperOffset()
|
||||
@@ -67,7 +69,12 @@ class MakeShrinkMap(object):
|
||||
shrunk = []
|
||||
|
||||
# Increase the shrink ratio every time we get multiple polygon returned back
|
||||
possible_ratios = np.arange(self.shrink_ratio, 1, self.shrink_ratio)
|
||||
shrink_ratio = self.shrink_ratio
|
||||
if "epoch" in data and hasattr(self, "_base_shrink_ratio"):
|
||||
shrink_ratio = self._base_shrink_ratio + 0.2 * data[
|
||||
"epoch"
|
||||
] / float(self._total_epoch)
|
||||
possible_ratios = np.arange(shrink_ratio, 1, shrink_ratio)
|
||||
np.append(possible_ratios, 1)
|
||||
# print(possible_ratios)
|
||||
for ratio in possible_ratios:
|
||||
|
||||
@@ -23,6 +23,7 @@ import sys
|
||||
import cv2
|
||||
import numpy as np
|
||||
import math
|
||||
import random
|
||||
from PIL import Image
|
||||
from paddle import get_device
|
||||
|
||||
@@ -209,6 +210,7 @@ class DetResizeForTest(object):
|
||||
super(DetResizeForTest, self).__init__()
|
||||
self.resize_type = 0
|
||||
self.keep_ratio = False
|
||||
self.max_side_limit = kwargs.get("max_side_limit", 4000)
|
||||
if "image_shape" in kwargs:
|
||||
self.image_shape = kwargs["image_shape"]
|
||||
self.resize_type = 1
|
||||
@@ -299,6 +301,13 @@ class DetResizeForTest(object):
|
||||
raise Exception("not support limit type, image ")
|
||||
resize_h = int(h * ratio)
|
||||
resize_w = int(w * ratio)
|
||||
if max(resize_h, resize_w) > self.max_side_limit:
|
||||
print(
|
||||
f"Resized image size ({resize_h}x{resize_w}) exceeds max_side_limit of {self.max_side_limit}. "
|
||||
f"Resizing to fit within limit."
|
||||
)
|
||||
ratio = float(self.max_side_limit) / max(resize_h, resize_w)
|
||||
resize_h, resize_w = int(resize_h * ratio), int(resize_w * ratio)
|
||||
|
||||
resize_h = max(int(round(resize_h / 32) * 32), 32)
|
||||
resize_w = max(int(round(resize_w / 32) * 32), 32)
|
||||
@@ -534,3 +543,150 @@ class GrayImageChannelFormat(object):
|
||||
|
||||
data["src_image"] = img
|
||||
return data
|
||||
|
||||
|
||||
class RandomPerspective(object):
|
||||
"""Random perspective transform for OCR detection training.
|
||||
|
||||
Operates on data["image"] (H,W,C) and data["polys"] (N, P, 2).
|
||||
Should be placed after IaaAugment and before EastRandomCropData.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
prob=0.3,
|
||||
degrees=0.0,
|
||||
scale=0.2,
|
||||
shear=5.0,
|
||||
perspective=0.0002,
|
||||
fit_output=True,
|
||||
fill_value=(123.675, 116.28, 103.53),
|
||||
min_area_ratio=0.1,
|
||||
**kwargs,
|
||||
):
|
||||
self.prob = prob
|
||||
self.degrees = degrees
|
||||
self.scale = scale
|
||||
self.shear = shear
|
||||
self.perspective = perspective
|
||||
self.fit_output = fit_output
|
||||
self.min_area_ratio = min_area_ratio
|
||||
if isinstance(fill_value, (int, float)):
|
||||
fill_value = (fill_value,) * 3
|
||||
self.fill_value = tuple(fill_value)
|
||||
|
||||
def __call__(self, data):
|
||||
if random.random() > self.prob:
|
||||
return data
|
||||
|
||||
im = data["image"]
|
||||
h, w = im.shape[:2]
|
||||
|
||||
# Build perspective matrix
|
||||
M_core = self._get_core_matrix(h, w)
|
||||
|
||||
# Compute output bounds
|
||||
corners = np.array([[0, 0], [w, 0], [w, h], [0, h]], dtype=np.float32).reshape(
|
||||
-1, 1, 2
|
||||
)
|
||||
warped_corners = cv2.perspectiveTransform(corners, M_core)
|
||||
x_min, y_min = warped_corners.min(axis=0).ravel()
|
||||
x_max, y_max = warped_corners.max(axis=0).ravel()
|
||||
|
||||
if self.fit_output:
|
||||
new_w = int(np.ceil(x_max) - np.floor(x_min))
|
||||
new_h = int(np.ceil(y_max) - np.floor(y_min))
|
||||
T_fit = np.eye(3, dtype=np.float32)
|
||||
T_fit[0, 2] = -np.floor(x_min)
|
||||
T_fit[1, 2] = -np.floor(y_min)
|
||||
M = T_fit @ M_core
|
||||
target_size = (new_w, new_h)
|
||||
else:
|
||||
T_orig = np.eye(3, dtype=np.float32)
|
||||
T_orig[0, 2] = w / 2.0
|
||||
T_orig[1, 2] = h / 2.0
|
||||
M = T_orig @ M_core
|
||||
target_size = (w, h)
|
||||
|
||||
# Warp image
|
||||
transformed_im = cv2.warpPerspective(
|
||||
im,
|
||||
M,
|
||||
target_size,
|
||||
flags=cv2.INTER_LINEAR,
|
||||
borderMode=cv2.BORDER_CONSTANT,
|
||||
borderValue=self.fill_value,
|
||||
)
|
||||
data["image"] = transformed_im
|
||||
|
||||
# Transform polys
|
||||
polys = data["polys"]
|
||||
ignore_tags = data["ignore_tags"]
|
||||
texts = data["texts"]
|
||||
|
||||
if len(polys) > 0:
|
||||
# polys: (N, P, 2) — flatten to (N*P, 1, 2) for perspectiveTransform
|
||||
n = len(polys)
|
||||
points_per_poly = (
|
||||
polys[0].shape[0] if hasattr(polys[0], "shape") else len(polys[0])
|
||||
)
|
||||
all_points = np.array(polys, dtype=np.float32).reshape(-1, 1, 2)
|
||||
|
||||
warped_pts = cv2.perspectiveTransform(all_points, M)
|
||||
warped_pts = warped_pts.reshape(n, points_per_poly, 2)
|
||||
|
||||
# Compute original areas for filtering
|
||||
orig_areas = np.array(
|
||||
[
|
||||
cv2.contourArea(p.astype(np.float32))
|
||||
for p in np.array(polys, dtype=np.float32)
|
||||
]
|
||||
)
|
||||
new_areas = np.array(
|
||||
[cv2.contourArea(p.astype(np.float32)) for p in warped_pts]
|
||||
)
|
||||
|
||||
tw, th = target_size
|
||||
# Filter: area ratio + center within bounds
|
||||
centers_x = warped_pts[:, :, 0].mean(axis=1)
|
||||
centers_y = warped_pts[:, :, 1].mean(axis=1)
|
||||
valid = (
|
||||
(new_areas > orig_areas * self.min_area_ratio)
|
||||
& (centers_x > 0)
|
||||
& (centers_x < tw)
|
||||
& (centers_y > 0)
|
||||
& (centers_y < th)
|
||||
)
|
||||
|
||||
valid_ids = np.where(valid)[0]
|
||||
data["polys"] = warped_pts[valid_ids]
|
||||
data["ignore_tags"] = [ignore_tags[i] for i in valid_ids]
|
||||
data["texts"] = [texts[i] for i in valid_ids]
|
||||
|
||||
return data
|
||||
|
||||
def _get_core_matrix(self, h, w):
|
||||
C = np.eye(3, dtype=np.float32)
|
||||
C[0, 2] = -w / 2
|
||||
C[1, 2] = -h / 2
|
||||
|
||||
# Normalize perspective coefficients using 640px as reference size
|
||||
# to ensure consistent distortion ratio across different image sizes
|
||||
ref_size = 640.0
|
||||
max_dim = max(h, w)
|
||||
p_normalized = self.perspective * (ref_size / max_dim)
|
||||
|
||||
P = np.eye(3, dtype=np.float32)
|
||||
P[2, 0] = random.uniform(-p_normalized, p_normalized)
|
||||
P[2, 1] = random.uniform(-p_normalized, p_normalized)
|
||||
|
||||
s = random.uniform(1 - self.scale, 1 + self.scale)
|
||||
a = random.uniform(-self.degrees, self.degrees)
|
||||
R = np.eye(3, dtype=np.float32)
|
||||
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
|
||||
|
||||
S = np.eye(3, dtype=np.float32)
|
||||
S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180)
|
||||
S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180)
|
||||
|
||||
return S @ R @ P @ C
|
||||
@@ -24,8 +24,12 @@ from __future__ import unicode_literals
|
||||
import numpy as np
|
||||
import cv2
|
||||
import random
|
||||
|
||||
from paddle import get_device
|
||||
|
||||
from shapely.geometry import Polygon, box as shapely_box
|
||||
from shapely import intersection
|
||||
|
||||
|
||||
def is_poly_in_rect(poly, x, y, w, h):
|
||||
poly = np.array(poly)
|
||||
@@ -77,6 +81,338 @@ def region_wise_random_select(regions, max_size):
|
||||
return xmin, xmax
|
||||
|
||||
|
||||
def get_min_rotated_rect_side(poly):
|
||||
"""
|
||||
Compute the minimum side length of the minimum bounding rotated rectangle of a polygon.
|
||||
"""
|
||||
poly = np.array(poly).astype(np.float32)
|
||||
if len(poly) < 3:
|
||||
return 0
|
||||
rect = cv2.minAreaRect(poly)
|
||||
width, height = rect[1]
|
||||
return min(width, height)
|
||||
|
||||
|
||||
def get_min_quad_side(quad):
|
||||
"""
|
||||
Compute the minimum side length of a quadrilateral.
|
||||
"""
|
||||
if len(quad) != 4:
|
||||
return 0
|
||||
quad = np.array(quad)
|
||||
sides = []
|
||||
for i in range(4):
|
||||
side = np.linalg.norm(quad[i] - quad[(i + 1) % 4])
|
||||
sides.append(side)
|
||||
return min(sides) if sides else 0
|
||||
|
||||
|
||||
def clip_poly_to_rect(poly, x, y, w, h):
|
||||
"""
|
||||
Clip a polygon to a rectangular region and return the clipped quadrilateral.
|
||||
|
||||
Args:
|
||||
poly: Original polygon vertices [[x1, y1], [x2, y2], ...]
|
||||
x, y, w, h: Position and size of the clipping rectangle
|
||||
|
||||
Returns:
|
||||
Clipped quadrilateral vertices, or None if the result is invalid.
|
||||
"""
|
||||
try:
|
||||
# Create polygon and clipping rectangle
|
||||
poly_shape = Polygon(poly)
|
||||
crop_rect = shapely_box(x, y, x + w, y + h)
|
||||
|
||||
# Compute intersection
|
||||
clipped = intersection(poly_shape, crop_rect)
|
||||
|
||||
# No intersection or empty
|
||||
if clipped.is_empty:
|
||||
return None
|
||||
|
||||
# Get intersection coordinates
|
||||
if clipped.geom_type == "Polygon":
|
||||
coords = list(clipped.exterior.coords[:-1]) # Remove duplicate last point
|
||||
elif clipped.geom_type == "MultiPolygon":
|
||||
# Multiple polygons, select the largest by area
|
||||
largest = max(clipped.geoms, key=lambda p: p.area)
|
||||
coords = list(largest.exterior.coords[:-1])
|
||||
elif clipped.geom_type == "GeometryCollection":
|
||||
# Extract polygons from geometry collection
|
||||
polygons = [g for g in clipped.geoms if g.geom_type == "Polygon"]
|
||||
if not polygons:
|
||||
return None
|
||||
largest = max(polygons, key=lambda p: p.area)
|
||||
coords = list(largest.exterior.coords[:-1])
|
||||
else:
|
||||
return None
|
||||
|
||||
# Less than 3 points, invalid
|
||||
if len(coords) <= 3:
|
||||
return None
|
||||
|
||||
# Convert to numpy array
|
||||
coords = np.array(coords)
|
||||
|
||||
# Exactly 4 points, return directly
|
||||
if len(coords) == 4:
|
||||
return coords
|
||||
|
||||
# More than 4 points, use Douglas-Peucker to simplify to quadrilateral
|
||||
# Output points are a subset of original coords (no out-of-bounds), IoU~0.99
|
||||
if len(coords) > 4:
|
||||
poly_cv = coords.reshape(-1, 1, 2).astype(np.float32)
|
||||
peri = cv2.arcLength(poly_cv, True)
|
||||
if peri < 1e-6:
|
||||
return None
|
||||
lo, hi = 0.0, 0.5
|
||||
best = None
|
||||
for _ in range(50):
|
||||
mid = (lo + hi) / 2
|
||||
approx = cv2.approxPolyDP(poly_cv, mid * peri, True)
|
||||
if len(approx) <= 4:
|
||||
best = approx
|
||||
hi = mid
|
||||
else:
|
||||
lo = mid
|
||||
if best is not None and len(best) >= 3:
|
||||
return best.reshape(-1, 2)
|
||||
return None
|
||||
|
||||
return coords
|
||||
except Exception as e:
|
||||
return None
|
||||
|
||||
|
||||
class RandomCrop(object):
|
||||
def __init__(
|
||||
self,
|
||||
size=(640, 640),
|
||||
max_tries=10,
|
||||
min_crop_side_ratio=0.1,
|
||||
keep_ratio=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.size = size
|
||||
self.max_tries = max_tries
|
||||
self.min_crop_side_ratio = min_crop_side_ratio
|
||||
self.keep_ratio = keep_ratio
|
||||
|
||||
def __call__(self, data):
|
||||
img = data["image"]
|
||||
text_polys = data["polys"]
|
||||
ignore_tags = data["ignore_tags"]
|
||||
texts = data["texts"]
|
||||
|
||||
# Separate care and ignore text boxes
|
||||
care_indices = [i for i, tag in enumerate(ignore_tags) if not tag]
|
||||
all_care_polys = [text_polys[i] for i in care_indices]
|
||||
|
||||
h, w, _ = img.shape
|
||||
|
||||
# If no valid text boxes, still need to resize and pad the image
|
||||
if len(all_care_polys) == 0:
|
||||
# Use entire image as crop region, skip crop loop
|
||||
crop_x, crop_y, crop_w, crop_h = 0, 0, w, h
|
||||
valid_care_data = []
|
||||
else:
|
||||
# Pre-compute char heights (min side of min bounding rotated rect) for all care boxes
|
||||
char_heights = np.array(
|
||||
[get_min_rotated_rect_side(poly) for poly in all_care_polys]
|
||||
)
|
||||
|
||||
# Try to find a suitable crop region
|
||||
valid_care_data = []
|
||||
for attempt in range(self.max_tries):
|
||||
# Randomly determine crop region width and height
|
||||
crop_w_min = min(int(w * self.min_crop_side_ratio), self.size[0])
|
||||
crop_w_max = int(self.size[0] * 3)
|
||||
crop_w = (
|
||||
w
|
||||
if crop_w_min >= crop_w_max
|
||||
else min(random.randint(crop_w_min, crop_w_max), w)
|
||||
)
|
||||
|
||||
crop_h_min = min(int(h * self.min_crop_side_ratio), self.size[1])
|
||||
crop_h_max = int(self.size[1] * 3)
|
||||
crop_h = (
|
||||
h
|
||||
if crop_h_min >= crop_h_max
|
||||
else min(random.randint(crop_h_min, crop_h_max), h)
|
||||
)
|
||||
|
||||
# Randomly determine crop region start position
|
||||
crop_x = 0 if crop_w >= w else random.randint(0, w - crop_w)
|
||||
crop_y = 0 if crop_h >= h else random.randint(0, h - crop_h)
|
||||
|
||||
# Check each care text box, clip and validate simultaneously (computed once)
|
||||
valid_care_data = []
|
||||
for care_idx, (poly, char_height) in enumerate(
|
||||
zip(all_care_polys, char_heights)
|
||||
):
|
||||
# Quick check: completely outside, skip
|
||||
if is_poly_outside_rect(poly, crop_x, crop_y, crop_w, crop_h):
|
||||
continue
|
||||
|
||||
# Completely inside, no clipping needed
|
||||
if is_poly_in_rect(poly, crop_x, crop_y, crop_w, crop_h):
|
||||
valid_care_data.append(
|
||||
(care_idx, None)
|
||||
) # None means no clipping needed
|
||||
continue
|
||||
|
||||
# Truncated box, clip and validate (executed once)
|
||||
clipped_poly = clip_poly_to_rect(
|
||||
poly, crop_x, crop_y, crop_w, crop_h
|
||||
)
|
||||
if clipped_poly is None:
|
||||
continue
|
||||
|
||||
# Validate clipped polygon - area check
|
||||
clipped_area = cv2.contourArea(clipped_poly.astype(np.float32))
|
||||
if clipped_area < 80:
|
||||
continue
|
||||
|
||||
# Validate - char height check
|
||||
clipped_char_height = get_min_rotated_rect_side(clipped_poly)
|
||||
if clipped_char_height < char_height * 0.35:
|
||||
continue
|
||||
|
||||
# Validate - min side length check (quadrilaterals only)
|
||||
if len(clipped_poly) == 4:
|
||||
min_side = get_min_quad_side(clipped_poly)
|
||||
if min_side < char_height * 0.35:
|
||||
continue
|
||||
|
||||
# All validations passed, save the clipped polygon
|
||||
valid_care_data.append((care_idx, clipped_poly))
|
||||
|
||||
# At least one valid text box, use this crop region
|
||||
if len(valid_care_data) >= 1:
|
||||
break
|
||||
else:
|
||||
# All attempts failed, use original region
|
||||
crop_x, crop_y, crop_w, crop_h = 0, 0, w, h
|
||||
valid_care_data = [(i, None) for i in range(len(all_care_polys))]
|
||||
|
||||
# Crop and scale image
|
||||
# Only shrink when crop region is larger than target size, otherwise just pad
|
||||
need_resize = crop_w > self.size[0] or crop_h > self.size[1]
|
||||
|
||||
if need_resize:
|
||||
# Crop region larger than target, need to shrink
|
||||
scale_w = self.size[0] / crop_w
|
||||
scale_h = self.size[1] / crop_h
|
||||
scale = min(scale_w, scale_h)
|
||||
h_resized = int(crop_h * scale)
|
||||
w_resized = int(crop_w * scale)
|
||||
else:
|
||||
# Crop region smaller than or equal to target, no upscaling
|
||||
scale = 1.0
|
||||
h_resized = crop_h
|
||||
w_resized = crop_w
|
||||
|
||||
if self.keep_ratio:
|
||||
# Random padding - compute padding size
|
||||
pad_h = self.size[1] - h_resized
|
||||
pad_w = self.size[0] - w_resized
|
||||
|
||||
# Randomly distribute padding to each side
|
||||
pad_top = random.randint(0, pad_h) if pad_h > 0 else 0
|
||||
pad_left = random.randint(0, pad_w) if pad_w > 0 else 0
|
||||
|
||||
# Resize cropped image (only when shrinking is needed)
|
||||
cropped_img = img[crop_y : crop_y + crop_h, crop_x : crop_x + crop_w]
|
||||
if need_resize:
|
||||
resized_img = cv2.resize(cropped_img, (w_resized, h_resized))
|
||||
else:
|
||||
resized_img = cropped_img
|
||||
|
||||
# Create padded image
|
||||
padimg = np.zeros((self.size[1], self.size[0], img.shape[2]), img.dtype)
|
||||
padimg[pad_top : pad_top + h_resized, pad_left : pad_left + w_resized] = (
|
||||
resized_img
|
||||
)
|
||||
img = padimg
|
||||
else:
|
||||
img = cv2.resize(
|
||||
img[crop_y : crop_y + crop_h, crop_x : crop_x + crop_w],
|
||||
tuple(self.size),
|
||||
)
|
||||
pad_left = 0
|
||||
pad_top = 0
|
||||
|
||||
# Build fast lookup set of valid care indices
|
||||
valid_care_indices_set = {care_idx for care_idx, _ in valid_care_data}
|
||||
|
||||
# Build mapping from care_idx to clipped polygon
|
||||
care_idx_to_clipped = {
|
||||
care_idx: clipped for care_idx, clipped in valid_care_data
|
||||
}
|
||||
|
||||
# Build output text box list
|
||||
text_polys_crop = []
|
||||
ignore_tags_crop = []
|
||||
texts_crop = []
|
||||
|
||||
for all_idx, (poly, text, tag) in enumerate(
|
||||
zip(text_polys, texts, ignore_tags)
|
||||
):
|
||||
if tag:
|
||||
# Ignore text box, simple processing
|
||||
if not is_poly_outside_rect(poly, crop_x, crop_y, crop_w, crop_h):
|
||||
adjusted_poly = (poly - (crop_x, crop_y)) * scale + (
|
||||
pad_left,
|
||||
pad_top,
|
||||
)
|
||||
adjusted_poly[:, 0] = np.clip(adjusted_poly[:, 0], 0, self.size[0])
|
||||
adjusted_poly[:, 1] = np.clip(adjusted_poly[:, 1], 0, self.size[1])
|
||||
text_polys_crop.append(adjusted_poly.tolist())
|
||||
ignore_tags_crop.append(tag)
|
||||
texts_crop.append(text)
|
||||
else:
|
||||
# Care text box, find corresponding care_idx
|
||||
try:
|
||||
care_idx = care_indices.index(all_idx)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# Check if this is a valid text box
|
||||
if care_idx not in valid_care_indices_set:
|
||||
continue
|
||||
|
||||
# Get clipped polygon (if any)
|
||||
clipped_poly = care_idx_to_clipped[care_idx]
|
||||
|
||||
if clipped_poly is None:
|
||||
# Completely inside, use original polygon
|
||||
adjusted_poly = (poly - (crop_x, crop_y)) * scale + (
|
||||
pad_left,
|
||||
pad_top,
|
||||
)
|
||||
else:
|
||||
# Use clipped polygon
|
||||
adjusted_poly = (clipped_poly - (crop_x, crop_y)) * scale + (
|
||||
pad_left,
|
||||
pad_top,
|
||||
)
|
||||
|
||||
text_polys_crop.append(adjusted_poly.tolist())
|
||||
ignore_tags_crop.append(tag)
|
||||
texts_crop.append(text)
|
||||
data["image"] = img
|
||||
# Pad polygons to uniform point count to avoid inhomogeneous array error
|
||||
if text_polys_crop:
|
||||
max_points = max(len(p) for p in text_polys_crop)
|
||||
for i, poly in enumerate(text_polys_crop):
|
||||
if len(poly) < max_points:
|
||||
text_polys_crop[i] = poly + [poly[-1]] * (max_points - len(poly))
|
||||
data["polys"] = np.array(text_polys_crop, dtype=np.float32)
|
||||
data["ignore_tags"] = ignore_tags_crop
|
||||
data["texts"] = texts_crop
|
||||
return data
|
||||
|
||||
|
||||
def crop_area(im, text_polys, min_crop_side_ratio, max_tries):
|
||||
h, w, _ = im.shape
|
||||
h_array = np.zeros(h, dtype=np.int32)
|
||||
|
||||
+313
-25
@@ -18,10 +18,156 @@ import os
|
||||
import json
|
||||
import random
|
||||
import traceback
|
||||
import multiprocessing
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import threading
|
||||
import concurrent.futures
|
||||
from collections import OrderedDict
|
||||
from paddle.io import Dataset
|
||||
from .imaug import transform, create_operators
|
||||
from paddle import get_device
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Per-worker-process URL prefetch cache
|
||||
#
|
||||
# Each DataLoader worker is a forked process with its own copy of
|
||||
# these globals. The thread pool and LRU cache are therefore
|
||||
# completely independent across workers — no cross-process locking
|
||||
# needed, and memory usage is bounded per worker.
|
||||
#
|
||||
# Memory budget (per worker):
|
||||
# _URL_CACHE_MAX × avg_image_size ≈ 200 × 270 KB ≈ 54 MB
|
||||
# With num_workers=4 the total extra footprint is ~216 MB.
|
||||
#
|
||||
# How prefetch works:
|
||||
# _ensure_index_map() fires inside the worker when an epoch changes.
|
||||
# It calls _prefetch_epoch_urls(), which scans the new _index_map,
|
||||
# picks the first _URL_PREFETCH_SUBMIT URL entries (epoch order ≈
|
||||
# access order), and submits them to the background thread pool.
|
||||
# _load_image_bytes() checks the cache / in-flight future before
|
||||
# falling back to a synchronous download.
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
_URL_CACHE_MAX = 200 # max cached images per worker
|
||||
_URL_PREFETCH_SUBMIT = 200 # URL items submitted to thread pool per epoch
|
||||
|
||||
# LRU cache: url -> bytes
|
||||
_url_cache: "OrderedDict[str, bytes]" = OrderedDict()
|
||||
_url_cache_lock = threading.Lock()
|
||||
|
||||
# In-flight futures: url -> Future
|
||||
_url_futures: "dict[str, concurrent.futures.Future]" = {}
|
||||
_url_futures_lock = threading.Lock()
|
||||
|
||||
# Lazily created per-process thread pool
|
||||
_url_executor: "concurrent.futures.ThreadPoolExecutor | None" = None
|
||||
_url_executor_lock = threading.Lock()
|
||||
|
||||
|
||||
def _get_url_executor():
|
||||
global _url_executor
|
||||
if _url_executor is None:
|
||||
with _url_executor_lock:
|
||||
if _url_executor is None:
|
||||
_url_executor = concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=4,
|
||||
thread_name_prefix="url_prefetch",
|
||||
)
|
||||
return _url_executor
|
||||
|
||||
|
||||
def _encode_url(url):
|
||||
"""Percent-encode non-ASCII characters in the URL path so that
|
||||
urllib can handle URLs containing CJK or other non-ASCII filenames.
|
||||
Scheme, netloc, query and fragment are left untouched.
|
||||
"""
|
||||
parts = urllib.parse.urlparse(url)
|
||||
encoded_path = urllib.parse.quote(parts.path, safe="/:@!$&'()*+,;=")
|
||||
return urllib.parse.urlunparse(parts._replace(path=encoded_path))
|
||||
|
||||
|
||||
def _download_url_bytes(url):
|
||||
"""Download *url*, store in LRU cache, remove from futures dict.
|
||||
The futures entry is always cleaned up (success or failure) so that
|
||||
a failed URL can be retried on the next access.
|
||||
"""
|
||||
encoded = _encode_url(url)
|
||||
try:
|
||||
with urllib.request.urlopen(encoded, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
except Exception:
|
||||
with _url_futures_lock:
|
||||
_url_futures.pop(url, None)
|
||||
raise
|
||||
with _url_cache_lock:
|
||||
if url not in _url_cache:
|
||||
if len(_url_cache) >= _URL_CACHE_MAX:
|
||||
_url_cache.popitem(last=False) # evict LRU entry
|
||||
_url_cache[url] = data
|
||||
else:
|
||||
_url_cache.move_to_end(url)
|
||||
with _url_futures_lock:
|
||||
_url_futures.pop(url, None)
|
||||
return data
|
||||
|
||||
|
||||
def _submit_url_prefetch(url):
|
||||
"""Submit a background download for *url* if not already cached/in-flight."""
|
||||
with _url_cache_lock:
|
||||
if url in _url_cache:
|
||||
return
|
||||
with _url_futures_lock:
|
||||
if url in _url_futures:
|
||||
return
|
||||
future = _get_url_executor().submit(_download_url_bytes, url)
|
||||
_url_futures[url] = future
|
||||
|
||||
|
||||
def _prefetch_epoch_urls(index_map, all_lines, delimiter):
|
||||
"""Scan *index_map* and submit the first _URL_PREFETCH_SUBMIT URL
|
||||
items for background download. Called inside worker processes."""
|
||||
submitted = 0
|
||||
for file_idx in index_map:
|
||||
if submitted >= _URL_PREFETCH_SUBMIT:
|
||||
break
|
||||
try:
|
||||
line = all_lines[file_idx].decode("utf-8")
|
||||
fname = line.strip("\n").split(delimiter)[0]
|
||||
if fname and fname[0] == "[": # JSON list — skip
|
||||
continue
|
||||
if fname.startswith("http://") or fname.startswith("https://"):
|
||||
_submit_url_prefetch(fname)
|
||||
submitted += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _load_image_bytes(img_path):
|
||||
"""Return raw image bytes. For URLs checks prefetch cache/future first."""
|
||||
if img_path.startswith("http://") or img_path.startswith("https://"):
|
||||
# 1. Cache hit — return immediately
|
||||
with _url_cache_lock:
|
||||
if img_path in _url_cache:
|
||||
_url_cache.move_to_end(img_path)
|
||||
return _url_cache[img_path]
|
||||
# 2. In-flight future — wait for background download to finish
|
||||
with _url_futures_lock:
|
||||
future = _url_futures.get(img_path)
|
||||
if future is not None:
|
||||
return future.result(timeout=60)
|
||||
# 3. Cold miss — download synchronously (also fills cache)
|
||||
return _download_url_bytes(img_path)
|
||||
with open(img_path, "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def _img_path_exists(img_path):
|
||||
"""Return True if the image source is accessible (local file exists or URL)."""
|
||||
if img_path.startswith("http://") or img_path.startswith("https://"):
|
||||
return True
|
||||
return os.path.exists(img_path)
|
||||
|
||||
|
||||
class SimpleDataSet(Dataset):
|
||||
def __init__(self, config, mode, logger, seed=None):
|
||||
@@ -39,6 +185,8 @@ class SimpleDataSet(Dataset):
|
||||
ratio_list = dataset_config.get("ratio_list", 1.0)
|
||||
if isinstance(ratio_list, (float, int)):
|
||||
ratio_list = [float(ratio_list)] * int(data_source_num)
|
||||
self.label_file_list = label_file_list
|
||||
self.ratio_list = ratio_list
|
||||
|
||||
assert (
|
||||
len(ratio_list) == data_source_num
|
||||
@@ -46,14 +194,98 @@ class SimpleDataSet(Dataset):
|
||||
self.data_dir = dataset_config["data_dir"]
|
||||
self.do_shuffle = loader_config["shuffle"]
|
||||
self.seed = seed
|
||||
logger.info("Initialize indexes of datasets:%s" % label_file_list)
|
||||
self.data_lines = self.get_image_info_list(label_file_list, ratio_list)
|
||||
self.data_idx_order_list = list(range(len(self.data_lines)))
|
||||
if self.mode == "train" and self.do_shuffle:
|
||||
self.shuffle_data_random()
|
||||
self.need_reset = True in [x < 1 for x in ratio_list]
|
||||
|
||||
logger.info("Initialize indexs of datasets:%s" % label_file_list)
|
||||
|
||||
if self.need_reset:
|
||||
# Pre-load all lines once (immutable, never re-read from disk).
|
||||
# Per-epoch ratio sampling is done via _index_map (virtual idx -> global idx).
|
||||
self._all_lines, self.file_boundaries = self._load_all_lines(
|
||||
label_file_list
|
||||
)
|
||||
self._index_map = self._generate_index_map(seed)
|
||||
self._cached_epoch = seed if seed is not None else 0
|
||||
# data_lines / data_idx_order_list kept for API compat but NOT used in __getitem__
|
||||
self.data_lines = self._all_lines
|
||||
self.data_idx_order_list = list(range(len(self._index_map)))
|
||||
else:
|
||||
self._all_lines = None
|
||||
self._index_map = None
|
||||
self._cached_epoch = None
|
||||
self.file_boundaries = None
|
||||
self.data_lines = self.get_image_info_list(label_file_list, ratio_list)
|
||||
self.data_idx_order_list = list(range(len(self.data_lines)))
|
||||
if self.mode == "train" and self.do_shuffle:
|
||||
self.shuffle_data_random()
|
||||
|
||||
# Shared epoch value: workers read this via shared memory to detect epoch changes
|
||||
self._shared_epoch = multiprocessing.Value("i", seed if seed is not None else 0)
|
||||
|
||||
self.ops = create_operators(dataset_config["transforms"], global_config)
|
||||
self.ext_op_transform_idx = dataset_config.get("ext_op_transform_idx", 2)
|
||||
self.need_reset = True in [x < 1 for x in ratio_list]
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Data loading helpers
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _load_all_lines(self, file_list):
|
||||
"""Read all label files once. Returns (all_lines, file_boundaries)."""
|
||||
if isinstance(file_list, str):
|
||||
file_list = [file_list]
|
||||
all_lines = []
|
||||
boundaries = [0]
|
||||
for f in file_list:
|
||||
with open(f, "rb") as fh:
|
||||
lines = fh.readlines()
|
||||
all_lines.extend(lines)
|
||||
boundaries.append(len(all_lines))
|
||||
return all_lines, boundaries
|
||||
|
||||
def _generate_index_map(self, seed):
|
||||
"""Generate virtual-index -> global-index mapping.
|
||||
|
||||
Replicates the EXACT sampling logic of original get_image_info_list +
|
||||
shuffle_data_random: for each file, random.seed(seed) then
|
||||
random.sample to pick indices, then random.seed(seed) + shuffle.
|
||||
|
||||
Since random.sample(population, k) with the same seed selects the
|
||||
same POSITIONS regardless of population type, sampling from
|
||||
range(start, end) yields the same positions as from lines[start:end].
|
||||
"""
|
||||
sampled = []
|
||||
for i in range(len(self.ratio_list)):
|
||||
start = self.file_boundaries[i]
|
||||
end = self.file_boundaries[i + 1]
|
||||
file_size = end - start
|
||||
count = round(file_size * self.ratio_list[i])
|
||||
if self.mode == "train" or self.ratio_list[i] < 1.0:
|
||||
random.seed(seed)
|
||||
sampled.extend(random.sample(range(start, end), count))
|
||||
else:
|
||||
sampled.extend(range(start, end))
|
||||
if self.mode == "train" and self.do_shuffle:
|
||||
random.seed(seed)
|
||||
random.shuffle(sampled)
|
||||
return sampled
|
||||
|
||||
def _ensure_index_map(self):
|
||||
"""Lazily rebuild _index_map when worker detects epoch change via shared memory.
|
||||
Also triggers URL prefetch on first call (epoch 0) and on every epoch change.
|
||||
"""
|
||||
if self._all_lines is None:
|
||||
return
|
||||
current_epoch = self._shared_epoch.value
|
||||
epoch_changed = current_epoch != self._cached_epoch
|
||||
first_call = not getattr(self, "_url_prefetch_initialized", False)
|
||||
|
||||
if epoch_changed:
|
||||
self._index_map = self._generate_index_map(current_epoch)
|
||||
self._cached_epoch = current_epoch
|
||||
|
||||
if epoch_changed or first_call:
|
||||
self._url_prefetch_initialized = True
|
||||
_prefetch_epoch_urls(self._index_map, self._all_lines, self.delimiter)
|
||||
|
||||
def get_image_info_list(self, file_list, ratio_list):
|
||||
if isinstance(file_list, str):
|
||||
@@ -73,6 +305,38 @@ class SimpleDataSet(Dataset):
|
||||
random.shuffle(self.data_lines)
|
||||
return
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Epoch update (called from main process each epoch)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def reset_data_lines(self, seed=None, epoch=None):
|
||||
"""Signal new epoch to persistent workers via shared memory.
|
||||
|
||||
Workers lazily rebuild their _index_map on next __getitem__ call.
|
||||
No disk I/O, no dataloader reconstruction.
|
||||
"""
|
||||
self.seed = seed
|
||||
epoch_val = epoch if epoch is not None else (seed if seed is not None else 0)
|
||||
self._shared_epoch.value = int(epoch_val)
|
||||
|
||||
if self._all_lines is not None:
|
||||
# Update main-process index_map (used by len() and batch_sampler)
|
||||
self._index_map = self._generate_index_map(seed)
|
||||
self._cached_epoch = int(epoch_val)
|
||||
self.data_idx_order_list = list(range(len(self._index_map)))
|
||||
else:
|
||||
# Fallback for non-ratio cases
|
||||
self.data_lines = self.get_image_info_list(
|
||||
self.label_file_list, self.ratio_list
|
||||
)
|
||||
self.data_idx_order_list = list(range(len(self.data_lines)))
|
||||
if self.mode == "train" and self.do_shuffle:
|
||||
self.shuffle_data_random()
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Data access
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _try_parse_filename_list(self, file_name):
|
||||
# multiple images -> one gt label
|
||||
if len(file_name) > 0 and file_name[0] == "[":
|
||||
@@ -93,20 +357,32 @@ class SimpleDataSet(Dataset):
|
||||
ext_data = []
|
||||
|
||||
while len(ext_data) < ext_data_num:
|
||||
file_idx = self.data_idx_order_list[np.random.randint(self.__len__())]
|
||||
data_line = self.data_lines[file_idx]
|
||||
if self._index_map is not None:
|
||||
# Sample from current epoch's subset (same as original)
|
||||
self._ensure_index_map()
|
||||
rand_virtual = np.random.randint(len(self._index_map))
|
||||
file_idx = self._index_map[rand_virtual]
|
||||
data_line = self._all_lines[file_idx]
|
||||
else:
|
||||
file_idx = self.data_idx_order_list[np.random.randint(self.__len__())]
|
||||
data_line = self.data_lines[file_idx]
|
||||
data_line = data_line.decode("utf-8")
|
||||
substr = data_line.strip("\n").split(self.delimiter)
|
||||
file_name = substr[0]
|
||||
file_name = self._try_parse_filename_list(file_name)
|
||||
label = substr[1]
|
||||
img_path = os.path.join(self.data_dir, file_name)
|
||||
img_path = (
|
||||
file_name
|
||||
if file_name.startswith("http://") or file_name.startswith("https://")
|
||||
else os.path.join(self.data_dir, file_name)
|
||||
)
|
||||
data = {"img_path": img_path, "label": label}
|
||||
if not os.path.exists(img_path):
|
||||
if not _img_path_exists(img_path):
|
||||
continue
|
||||
try:
|
||||
data["image"] = _load_image_bytes(img_path)
|
||||
except Exception:
|
||||
continue
|
||||
with open(data["img_path"], "rb") as f:
|
||||
img = f.read()
|
||||
data["image"] = img
|
||||
data = transform(data, load_data_ops)
|
||||
|
||||
if data is None:
|
||||
@@ -118,23 +394,31 @@ class SimpleDataSet(Dataset):
|
||||
return ext_data
|
||||
|
||||
def __getitem__(self, idx):
|
||||
file_idx = self.data_idx_order_list[idx]
|
||||
data_line = self.data_lines[file_idx]
|
||||
if self._index_map is not None:
|
||||
self._ensure_index_map()
|
||||
file_idx = self._index_map[idx]
|
||||
data_line = self._all_lines[file_idx]
|
||||
else:
|
||||
file_idx = self.data_idx_order_list[idx]
|
||||
data_line = self.data_lines[file_idx]
|
||||
try:
|
||||
data_line = data_line.decode("utf-8")
|
||||
substr = data_line.strip("\n").split(self.delimiter)
|
||||
file_name = substr[0]
|
||||
file_name = self._try_parse_filename_list(file_name)
|
||||
label = substr[1]
|
||||
img_path = os.path.join(self.data_dir, file_name)
|
||||
img_path = (
|
||||
file_name
|
||||
if file_name.startswith("http://") or file_name.startswith("https://")
|
||||
else os.path.join(self.data_dir, file_name)
|
||||
)
|
||||
data = {"img_path": img_path, "label": label}
|
||||
if not os.path.exists(img_path):
|
||||
if not _img_path_exists(img_path):
|
||||
raise Exception("{} does not exist!".format(img_path))
|
||||
with open(data["img_path"], "rb") as f:
|
||||
img = f.read()
|
||||
data["image"] = img
|
||||
data["image"] = _load_image_bytes(img_path)
|
||||
data["ext_data"] = self.get_ext_data()
|
||||
data["filename"] = data["img_path"]
|
||||
data["epoch"] = self._shared_epoch.value
|
||||
outs = transform(data, self.ops)
|
||||
except:
|
||||
self.logger.error(
|
||||
@@ -154,6 +438,8 @@ class SimpleDataSet(Dataset):
|
||||
return outs
|
||||
|
||||
def __len__(self):
|
||||
if self._index_map is not None:
|
||||
return len(self._index_map)
|
||||
return len(self.data_idx_order_list)
|
||||
|
||||
|
||||
@@ -230,13 +516,15 @@ class MultiScaleDataSet(SimpleDataSet):
|
||||
file_name = substr[0]
|
||||
file_name = self._try_parse_filename_list(file_name)
|
||||
label = substr[1]
|
||||
img_path = os.path.join(self.data_dir, file_name)
|
||||
img_path = (
|
||||
file_name
|
||||
if file_name.startswith("http://") or file_name.startswith("https://")
|
||||
else os.path.join(self.data_dir, file_name)
|
||||
)
|
||||
data = {"img_path": img_path, "label": label}
|
||||
if not os.path.exists(img_path):
|
||||
if not _img_path_exists(img_path):
|
||||
raise Exception("{} does not exist!".format(img_path))
|
||||
with open(data["img_path"], "rb") as f:
|
||||
img = f.read()
|
||||
data["image"] = img
|
||||
data["image"] = _load_image_bytes(img_path)
|
||||
data["ext_data"] = self.get_ext_data()
|
||||
outs = transform(data, self.ops[:-1])
|
||||
if outs is not None:
|
||||
|
||||
@@ -159,3 +159,126 @@ class BCELoss(nn.Layer):
|
||||
def forward(self, input, label, mask=None, weight=None, name=None):
|
||||
loss = F.binary_cross_entropy(input, label, reduction=self.reduction)
|
||||
return loss
|
||||
|
||||
|
||||
class MaskedFocalLoss(nn.Layer):
|
||||
"""
|
||||
Binary Focal Loss with mask support, designed for text segmentation tasks.
|
||||
|
||||
Focal Loss addresses class imbalance by down-weighting easy examples and
|
||||
focusing training on hard examples:
|
||||
FL(p_t) = -alpha_t * (1 - p_t)^gamma * log(p_t)
|
||||
|
||||
Compared to OHEM (which hard-selects a fixed ratio of negatives), Focal Loss
|
||||
applies a continuous per-pixel weight that gracefully scales with difficulty,
|
||||
making it a strictly superior drop-in for the OHEM + DiceLoss pattern when
|
||||
DiceLoss returns a scalar and OHEM has no discriminating effect.
|
||||
|
||||
Args:
|
||||
alpha (float): Balancing factor for the positive (text) class.
|
||||
Since text pixels are a small minority, alpha > 0.5 gives them
|
||||
higher weight. Default: 0.75.
|
||||
gamma (float): Focusing parameter. gamma=0 reduces to masked BCE.
|
||||
gamma=2 is the standard value from the original Focal Loss paper.
|
||||
Default: 2.0.
|
||||
eps (float): Small constant for numerical stability. Default: 1e-6.
|
||||
"""
|
||||
|
||||
def __init__(self, alpha=0.25, gamma=2.0, eps=1e-6):
|
||||
super(MaskedFocalLoss, self).__init__()
|
||||
self.alpha = alpha
|
||||
self.gamma = gamma
|
||||
self.eps = eps
|
||||
|
||||
def forward(self, pred, gt, mask):
|
||||
"""
|
||||
Args:
|
||||
pred (Tensor): Predicted probability map, shape (B, H, W), in [0, 1].
|
||||
(i.e. after sigmoid — the direct output of DBHead.binarize)
|
||||
gt (Tensor): Binary ground-truth map, shape (B, H, W), values 0 or 1.
|
||||
mask (Tensor): Valid-pixel mask, shape (B, H, W), values 0 or 1.
|
||||
Pixels with mask=0 are ignored regions (e.g. too-small text).
|
||||
Returns:
|
||||
Tensor: Scalar focal loss averaged over valid (mask=1) pixels.
|
||||
"""
|
||||
# F.sigmoid_focal_loss expects a logit (pre-sigmoid) input and applies
|
||||
# sigmoid internally using the numerically stable log-sum-exp form:
|
||||
# log(σ(x)) = -softplus(-x), log(1-σ(x)) = -softplus(x)
|
||||
# This avoids the log(0) issue of the manual implementation.
|
||||
# Since pred is already a probability (post-sigmoid from DBHead), we
|
||||
# invert it: logit = log(p / (1-p)). The round-trip is numerically safe
|
||||
# after clamping, and the stable path inside paddle takes over from there.
|
||||
pred = paddle.clip(pred, self.eps, 1.0 - self.eps)
|
||||
logit = paddle.log(pred / (1.0 - pred))
|
||||
|
||||
# Per-pixel focal loss, shape (B, H, W)
|
||||
# reduction='none' so we can apply the mask ourselves
|
||||
loss = F.sigmoid_focal_loss(
|
||||
logit,
|
||||
gt,
|
||||
normalizer=None,
|
||||
alpha=self.alpha,
|
||||
gamma=self.gamma,
|
||||
reduction="none",
|
||||
)
|
||||
|
||||
# Average over valid (mask=1) pixels only
|
||||
return (loss * mask).sum() / (mask.sum() + self.eps)
|
||||
|
||||
|
||||
class DiceFocalLoss(nn.Layer):
|
||||
"""
|
||||
Combined DiceLoss + MaskedFocalLoss for binary text segmentation.
|
||||
|
||||
Rationale for the combination:
|
||||
- DiceLoss optimizes the global F1 / region overlap between prediction and GT.
|
||||
It is naturally robust to class imbalance (text vs background) because it
|
||||
normalizes by the sum of both sets, not by pixel count.
|
||||
- MaskedFocalLoss provides per-pixel supervision with adaptive hard-example
|
||||
weighting. It compensates for DiceLoss being a global metric that cannot
|
||||
distinguish which specific pixels are mispredicted.
|
||||
Together they provide complementary supervision: DiceLoss for global shape
|
||||
quality, FocalLoss for pixel-level precision on ambiguous boundaries.
|
||||
|
||||
This design follows the Dice + Focal combination used in mmsegmentation and
|
||||
segmentation_models_pytorch for binary segmentation with class imbalance.
|
||||
|
||||
This class is a drop-in replacement for BalanceLoss when main_loss_type is
|
||||
'DiceLoss' — both share the same forward(pred, gt, mask) signature and
|
||||
return a scalar.
|
||||
|
||||
Args:
|
||||
dice_weight (float): Weight for the DiceLoss term. Default: 1.0.
|
||||
focal_weight (float): Weight for the MaskedFocalLoss term. Default: 1.0.
|
||||
focal_alpha (float): Positive-class balancing factor for FocalLoss.
|
||||
Default: 0.75.
|
||||
focal_gamma (float): Focusing exponent for FocalLoss. Default: 2.0.
|
||||
eps (float): Numerical stability constant. Default: 1e-6.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dice_weight=1.0,
|
||||
focal_weight=1.0,
|
||||
focal_alpha=0.75,
|
||||
focal_gamma=2.0,
|
||||
eps=1e-6,
|
||||
):
|
||||
super(DiceFocalLoss, self).__init__()
|
||||
self.dice_weight = dice_weight
|
||||
self.focal_weight = focal_weight
|
||||
self.dice_loss = DiceLoss(eps=eps)
|
||||
self.focal_loss = MaskedFocalLoss(alpha=focal_alpha, gamma=focal_gamma, eps=eps)
|
||||
|
||||
def forward(self, pred, gt, mask=None):
|
||||
"""
|
||||
Args:
|
||||
pred (Tensor): Predicted probability map, shape (B, H, W), in [0, 1].
|
||||
gt (Tensor): Binary ground-truth shrink map, shape (B, H, W).
|
||||
mask (Tensor): Valid-pixel mask, shape (B, H, W).
|
||||
Returns:
|
||||
Tensor: Scalar combined loss.
|
||||
"""
|
||||
loss_dice = self.dice_loss(pred, gt, mask)
|
||||
loss_focal = self.focal_loss(pred, gt, mask)
|
||||
return self.dice_weight * loss_dice + self.focal_weight * loss_focal
|
||||
@@ -23,7 +23,7 @@ from __future__ import print_function
|
||||
import paddle
|
||||
from paddle import nn
|
||||
|
||||
from .det_basic_loss import BalanceLoss, MaskL1Loss, DiceLoss
|
||||
from .det_basic_loss import BalanceLoss, MaskL1Loss, DiceLoss, DiceFocalLoss
|
||||
|
||||
|
||||
class DBLoss(nn.Layer):
|
||||
@@ -41,18 +41,40 @@ class DBLoss(nn.Layer):
|
||||
beta=10,
|
||||
ohem_ratio=3,
|
||||
eps=1e-6,
|
||||
aux_weight_p4=0.0,
|
||||
aux_weight_p3=0.0,
|
||||
aux_weight_p2=0.0,
|
||||
focal_alpha=0.25,
|
||||
focal_gamma=2.0,
|
||||
dice_weight=1.0,
|
||||
focal_weight=1.0,
|
||||
**kwargs,
|
||||
):
|
||||
super(DBLoss, self).__init__()
|
||||
self.alpha = alpha
|
||||
self.beta = beta
|
||||
self.dice_loss = DiceLoss(eps=eps)
|
||||
self.l1_loss = MaskL1Loss(eps=eps)
|
||||
self.bce_loss = BalanceLoss(
|
||||
balance_loss=balance_loss,
|
||||
main_loss_type=main_loss_type,
|
||||
negative_ratio=ohem_ratio,
|
||||
)
|
||||
if main_loss_type == "DiceFocalLoss":
|
||||
self.bce_loss = DiceFocalLoss(
|
||||
dice_weight=dice_weight,
|
||||
focal_weight=focal_weight,
|
||||
focal_alpha=focal_alpha,
|
||||
focal_gamma=focal_gamma,
|
||||
eps=eps,
|
||||
)
|
||||
self.dice_loss = self.bce_loss
|
||||
elif main_loss_type == "DiceLoss":
|
||||
self.bce_loss = BalanceLoss(
|
||||
balance_loss=balance_loss,
|
||||
main_loss_type=main_loss_type,
|
||||
negative_ratio=ohem_ratio,
|
||||
)
|
||||
self.dice_loss = DiceLoss(eps=eps)
|
||||
else:
|
||||
raise Exception("[DBLoss]: Unrecognized main loss type!")
|
||||
self.aux_weight_p4 = aux_weight_p4
|
||||
self.aux_weight_p3 = aux_weight_p3
|
||||
self.aux_weight_p2 = aux_weight_p2
|
||||
|
||||
def forward(self, predicts, labels):
|
||||
predict_maps = predicts["maps"]
|
||||
@@ -96,4 +118,29 @@ class DBLoss(nn.Layer):
|
||||
"loss_binary_maps": loss_binary_maps,
|
||||
"loss_cbn": cbn_loss,
|
||||
}
|
||||
|
||||
# Auxiliary loss
|
||||
for aux_key, aux_w in [
|
||||
("aux_maps_p4", self.aux_weight_p4),
|
||||
("aux_maps_p3", self.aux_weight_p3),
|
||||
("aux_maps_p2", self.aux_weight_p2),
|
||||
]:
|
||||
if aux_w > 0 and aux_key in predicts:
|
||||
aux_maps = predicts[aux_key]
|
||||
aux_shrink = aux_maps[:, 0, :, :]
|
||||
aux_threshold = aux_maps[:, 1, :, :]
|
||||
aux_binary = aux_maps[:, 2, :, :]
|
||||
l_shrink = self.alpha * self.bce_loss(
|
||||
aux_shrink, label_shrink_map, label_shrink_mask
|
||||
)
|
||||
l_threshold = self.beta * self.l1_loss(
|
||||
aux_threshold, label_threshold_map, label_threshold_mask
|
||||
)
|
||||
l_binary = self.dice_loss(
|
||||
aux_binary, label_shrink_map, label_shrink_mask
|
||||
)
|
||||
aux_loss = l_shrink + l_threshold + l_binary
|
||||
losses["loss_{}".format(aux_key)] = aux_loss
|
||||
losses["loss"] = losses["loss"] + aux_w * aux_loss
|
||||
|
||||
return losses
|
||||
@@ -23,6 +23,7 @@ def build_backbone(config, model_type):
|
||||
from .det_resnet_vd_sast import ResNet_SAST
|
||||
from .det_pp_lcnet import PPLCNet
|
||||
from .rec_lcnetv3 import PPLCNetV3
|
||||
from .rec_lcnetv4 import PPLCNetV4
|
||||
from .rec_hgnet import PPHGNet_small
|
||||
from .rec_vit import ViT
|
||||
from .det_pp_lcnet_v2 import PPLCNetV2_base
|
||||
@@ -37,6 +38,7 @@ def build_backbone(config, model_type):
|
||||
"ResNet_SAST",
|
||||
"PPLCNet",
|
||||
"PPLCNetV3",
|
||||
"PPLCNetV4",
|
||||
"PPHGNet_small",
|
||||
"PPLCNetV2_base",
|
||||
"RepSVTR_det",
|
||||
@@ -68,6 +70,7 @@ def build_backbone(config, model_type):
|
||||
from .rec_donut_swin import DonutSwinModel
|
||||
from .rec_shallow_cnn import ShallowCNN
|
||||
from .rec_lcnetv3 import PPLCNetV3
|
||||
from .rec_lcnetv4 import PPLCNetV4
|
||||
from .rec_hgnet import PPHGNet_small
|
||||
from .rec_vit_parseq import ViTParseQ
|
||||
from .rec_repvit import RepSVTR
|
||||
@@ -97,6 +100,7 @@ def build_backbone(config, model_type):
|
||||
"DenseNet",
|
||||
"ShallowCNN",
|
||||
"PPLCNetV3",
|
||||
"PPLCNetV4",
|
||||
"PPHGNet_small",
|
||||
"ViTParseQ",
|
||||
"ViT",
|
||||
|
||||
@@ -233,6 +233,7 @@ class LearnableRepLayer(nn.Layer):
|
||||
out = self.act(out)
|
||||
return out
|
||||
|
||||
@paddle.no_grad()
|
||||
def rep(self):
|
||||
if self.is_repped:
|
||||
return
|
||||
@@ -247,6 +248,14 @@ class LearnableRepLayer(nn.Layer):
|
||||
)
|
||||
self.reparam_conv.weight.set_value(kernel)
|
||||
self.reparam_conv.bias.set_value(bias)
|
||||
# Remove training branches to avoid duplicate parameter counting
|
||||
del self.conv_kxk
|
||||
if self.conv_1x1 is not None:
|
||||
del self.conv_1x1
|
||||
if self.identity is not None:
|
||||
del self.identity
|
||||
if hasattr(self, "id_tensor"):
|
||||
del self.id_tensor
|
||||
self.is_repped = True
|
||||
|
||||
def _pad_kernel_1x1_to_kxk(self, kernel1x1, pad):
|
||||
|
||||
@@ -0,0 +1,667 @@
|
||||
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
|
||||
import paddle
|
||||
import paddle.nn as nn
|
||||
import paddle.nn.functional as F
|
||||
from paddle import ParamAttr
|
||||
from paddle.nn.initializer import Constant
|
||||
from paddle.nn import (
|
||||
BatchNorm2D,
|
||||
Conv2D,
|
||||
GELU,
|
||||
Hardsigmoid,
|
||||
Hardswish,
|
||||
ReLU,
|
||||
)
|
||||
from paddle.regularizer import L2Decay
|
||||
|
||||
|
||||
NET_CONFIG_DET = {
|
||||
"tiny": {
|
||||
# stem(mid=16, out=32) channels: 32 → 48 → 64 → 160
|
||||
"stem": (16, 32),
|
||||
"blocks_s1": [[3, 32, 32, 1, True], [3, 32, 32, 1, False]],
|
||||
"blocks_s2": [
|
||||
[3, 32, 48, 2, False],
|
||||
[3, 48, 48, 1, True],
|
||||
[3, 48, 48, 1, False],
|
||||
],
|
||||
"blocks_s3": [
|
||||
[3, 48, 64, 2, False],
|
||||
[3, 64, 64, 1, True],
|
||||
[3, 64, 64, 1, False],
|
||||
[3, 64, 64, 1, True],
|
||||
[3, 64, 64, 1, False],
|
||||
],
|
||||
"blocks_s4": [
|
||||
[3, 64, 160, 2, False],
|
||||
[3, 160, 160, 1, True],
|
||||
[3, 160, 160, 1, False],
|
||||
],
|
||||
},
|
||||
"small": {
|
||||
# stem(mid=24, out=48) channels: 48 → 96 → 192 → 384
|
||||
"stem": (24, 48),
|
||||
"blocks_s1": [[3, 48, 48, 1, True], [3, 48, 48, 1, False]],
|
||||
"blocks_s2": [
|
||||
[3, 48, 96, 2, False],
|
||||
[3, 96, 96, 1, True],
|
||||
[3, 96, 96, 1, False],
|
||||
],
|
||||
"blocks_s3": [
|
||||
[3, 96, 192, 2, False],
|
||||
[3, 192, 192, 1, True],
|
||||
[3, 192, 192, 1, False],
|
||||
[3, 192, 192, 1, True],
|
||||
[3, 192, 192, 1, False],
|
||||
],
|
||||
"blocks_s4": [
|
||||
[3, 192, 384, 2, False],
|
||||
[3, 384, 384, 1, True],
|
||||
[3, 384, 384, 1, False],
|
||||
],
|
||||
},
|
||||
"medium": {
|
||||
# stem(mid=64, out=128) channels: 128 → 256 → 512 → 896
|
||||
"stem": (64, 128),
|
||||
"blocks_s1": [[3, 128, 128, 1, True], [3, 128, 128, 1, False]],
|
||||
"blocks_s2": [
|
||||
[3, 128, 256, 2, False],
|
||||
[3, 256, 256, 1, True],
|
||||
[3, 256, 256, 1, False],
|
||||
],
|
||||
"blocks_s3": [
|
||||
[3, 256, 512, 2, False],
|
||||
[3, 512, 512, 1, True],
|
||||
[3, 512, 512, 1, False],
|
||||
[3, 512, 512, 1, True],
|
||||
[3, 512, 512, 1, False],
|
||||
],
|
||||
"blocks_s4": [
|
||||
[3, 512, 896, 2, False],
|
||||
[3, 896, 896, 1, True],
|
||||
[3, 896, 896, 1, False],
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
NET_CONFIG_REC = {
|
||||
"tiny": {
|
||||
# stem: simple (2×Conv2D_BN+GELU, mid=24, out=48) channels: 48 → 96 → 160
|
||||
"stem": (24, 48),
|
||||
"stem_type": "simple",
|
||||
"blocks2": [[3, 48, 48, 1, True]],
|
||||
"blocks3": [[3, 48, 48, 1, False]],
|
||||
"blocks4": [
|
||||
[3, 48, 96, (2, 1), False],
|
||||
[3, 96, 96, 1, True],
|
||||
[3, 96, 96, 1, False],
|
||||
],
|
||||
"blocks5": [
|
||||
[3, 96, 160, (2, 1), False],
|
||||
[3, 160, 160, 1, True],
|
||||
[3, 160, 160, 1, False],
|
||||
[3, 160, 160, 1, False],
|
||||
],
|
||||
"blocks6": [],
|
||||
},
|
||||
"small": {
|
||||
# stem: branch StemBlock (mid=48, out=96) channels: 96 → 192 → 384
|
||||
"stem": (48, 96),
|
||||
"stem_type": "branch",
|
||||
"blocks2": [[3, 96, 96, 1, True]],
|
||||
"blocks3": [[3, 96, 96, 1, False], [3, 96, 96, 1, False]],
|
||||
"blocks4": [
|
||||
[3, 96, 192, (2, 1), False],
|
||||
[3, 192, 192, 1, True],
|
||||
[3, 192, 192, 1, False],
|
||||
[3, 192, 192, 1, True],
|
||||
[3, 192, 192, 1, False],
|
||||
[3, 192, 192, 1, True],
|
||||
[3, 192, 192, 1, False],
|
||||
],
|
||||
"blocks5": [
|
||||
[3, 192, 384, (2, 1), False],
|
||||
[3, 384, 384, 1, True],
|
||||
[3, 384, 384, 1, False],
|
||||
],
|
||||
"blocks6": [],
|
||||
},
|
||||
"base": {
|
||||
# stem: branch StemBlock (mid=64, out=128) channels: 128 → 384 → 640
|
||||
"stem": (64, 128),
|
||||
"stem_type": "branch",
|
||||
"blocks2": [[3, 128, 128, 1, True]],
|
||||
"blocks3": [[3, 128, 128, 1, False], [3, 128, 128, 1, False]],
|
||||
"blocks4": [
|
||||
[3, 128, 384, (2, 1), False],
|
||||
[3, 384, 384, 1, True],
|
||||
[3, 384, 384, 1, False],
|
||||
[3, 384, 384, 1, True],
|
||||
[3, 384, 384, 1, False],
|
||||
[3, 384, 384, 1, True],
|
||||
[3, 384, 384, 1, False],
|
||||
[3, 384, 384, 1, False],
|
||||
],
|
||||
"blocks5": [
|
||||
[3, 384, 640, (2, 1), False],
|
||||
[3, 640, 640, 1, True],
|
||||
[3, 640, 640, 1, False],
|
||||
[3, 640, 640, 1, True],
|
||||
],
|
||||
"blocks6": [],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class Conv2D_BN(nn.Sequential):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=1,
|
||||
stride=1,
|
||||
padding=0,
|
||||
groups=1,
|
||||
bn_weight_init=1.0,
|
||||
):
|
||||
super().__init__()
|
||||
self.add_sublayer(
|
||||
"conv",
|
||||
Conv2D(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride,
|
||||
padding,
|
||||
groups=groups,
|
||||
bias_attr=False,
|
||||
),
|
||||
)
|
||||
bn = BatchNorm2D(out_channels)
|
||||
Constant(1.0 if bn_weight_init == 1.0 else 0.0)(bn.weight)
|
||||
Constant(0.0)(bn.bias)
|
||||
self.add_sublayer("bn", bn)
|
||||
|
||||
@paddle.no_grad()
|
||||
def fuse(self):
|
||||
c, bn = self.conv, self.bn
|
||||
w = bn.weight / (bn._variance + bn._epsilon) ** 0.5
|
||||
w = c.weight * w[:, None, None, None]
|
||||
b = bn.bias - bn._mean * bn.weight / (bn._variance + bn._epsilon) ** 0.5
|
||||
m = Conv2D(
|
||||
w.shape[1] * c._groups,
|
||||
w.shape[0],
|
||||
w.shape[2:],
|
||||
stride=c._stride,
|
||||
padding=c._padding,
|
||||
groups=c._groups,
|
||||
)
|
||||
m.weight.set_value(w)
|
||||
m.bias.set_value(b)
|
||||
return m
|
||||
|
||||
|
||||
class ConvBNAct(nn.Layer):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
groups=1,
|
||||
use_act=True,
|
||||
lr_mult=1.0,
|
||||
):
|
||||
super().__init__()
|
||||
self.use_act = use_act
|
||||
self.is_repped = False
|
||||
self.conv = Conv2D(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride,
|
||||
padding=padding if isinstance(padding, str) else (kernel_size - 1) // 2,
|
||||
groups=groups,
|
||||
weight_attr=ParamAttr(learning_rate=lr_mult),
|
||||
bias_attr=False,
|
||||
)
|
||||
self.bn = BatchNorm2D(
|
||||
out_channels,
|
||||
weight_attr=ParamAttr(regularizer=L2Decay(0.0), learning_rate=lr_mult),
|
||||
bias_attr=ParamAttr(regularizer=L2Decay(0.0), learning_rate=lr_mult),
|
||||
)
|
||||
if self.use_act:
|
||||
self.act = ReLU()
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv(x)
|
||||
if not self.is_repped:
|
||||
x = self.bn(x)
|
||||
if self.use_act:
|
||||
x = self.act(x)
|
||||
return x
|
||||
|
||||
@paddle.no_grad()
|
||||
def rep(self):
|
||||
if self.is_repped:
|
||||
return
|
||||
c, bn = self.conv, self.bn
|
||||
w = bn.weight / (bn._variance + bn._epsilon) ** 0.5
|
||||
fused_w = c.weight * w[:, None, None, None]
|
||||
fused_b = bn.bias - bn._mean * bn.weight / (bn._variance + bn._epsilon) ** 0.5
|
||||
m = Conv2D(
|
||||
c._in_channels,
|
||||
c._out_channels,
|
||||
c._kernel_size,
|
||||
stride=c._stride,
|
||||
padding=c._padding,
|
||||
dilation=c._dilation,
|
||||
groups=c._groups,
|
||||
)
|
||||
m.weight.set_value(fused_w)
|
||||
m.bias.set_value(fused_b)
|
||||
self.conv = m
|
||||
del self.bn
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class StemBlock(nn.Layer):
|
||||
"""Multi-branch stem with total stride 4 (stem1 stride=2 + stem3 stride=2)."""
|
||||
|
||||
def __init__(self, in_channels=3, mid_channels=48, out_channels=96, lr_mult=1.0):
|
||||
super().__init__()
|
||||
self.is_repped = False
|
||||
self.stem1 = ConvBNAct(
|
||||
in_channels, mid_channels, 3, 2, use_act=True, lr_mult=lr_mult
|
||||
)
|
||||
self.stem2a = ConvBNAct(
|
||||
mid_channels,
|
||||
mid_channels // 2,
|
||||
2,
|
||||
1,
|
||||
padding="SAME",
|
||||
use_act=True,
|
||||
lr_mult=lr_mult,
|
||||
)
|
||||
self.stem2b = ConvBNAct(
|
||||
mid_channels // 2,
|
||||
mid_channels,
|
||||
2,
|
||||
1,
|
||||
padding="SAME",
|
||||
use_act=True,
|
||||
lr_mult=lr_mult,
|
||||
)
|
||||
self.stem3 = ConvBNAct(
|
||||
mid_channels * 2, mid_channels, 3, 2, use_act=True, lr_mult=lr_mult
|
||||
)
|
||||
self.stem4 = ConvBNAct(
|
||||
mid_channels, out_channels, 1, 1, use_act=True, lr_mult=lr_mult
|
||||
)
|
||||
self.pool = nn.MaxPool2D(kernel_size=2, stride=1, padding="SAME")
|
||||
|
||||
def forward(self, x):
|
||||
x = self.stem1(x)
|
||||
x2 = self.stem2b(self.stem2a(x))
|
||||
x1 = self.pool(x)
|
||||
x = self.stem4(self.stem3(paddle.concat([x1, x2], axis=1)))
|
||||
return x
|
||||
|
||||
def rep(self, fuse_lab=None):
|
||||
if self.is_repped:
|
||||
return
|
||||
for attr in ("stem1", "stem2a", "stem2b", "stem3", "stem4"):
|
||||
getattr(self, attr).rep()
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class SELayer(nn.Layer):
|
||||
def __init__(self, channel, reduction=4, lr_mult=1.0):
|
||||
super().__init__()
|
||||
self.conv1 = Conv2D(
|
||||
channel,
|
||||
channel // reduction,
|
||||
1,
|
||||
weight_attr=ParamAttr(learning_rate=lr_mult),
|
||||
bias_attr=ParamAttr(learning_rate=lr_mult),
|
||||
)
|
||||
self.relu = ReLU()
|
||||
self.conv2 = Conv2D(
|
||||
channel // reduction,
|
||||
channel,
|
||||
1,
|
||||
weight_attr=ParamAttr(learning_rate=lr_mult),
|
||||
bias_attr=ParamAttr(learning_rate=lr_mult),
|
||||
)
|
||||
self.hardsigmoid = Hardsigmoid()
|
||||
|
||||
def forward(self, x):
|
||||
identity = x
|
||||
x = x.mean(axis=[2, 3], keepdim=True)
|
||||
x = self.relu(self.conv1(x))
|
||||
x = self.hardsigmoid(self.conv2(x))
|
||||
return paddle.multiply(x=identity, y=x)
|
||||
|
||||
|
||||
class RepDWConv(nn.Layer):
|
||||
"""Reparameterizable depthwise convolution.
|
||||
|
||||
Training: 3-branch (3×3 DW + 1×1 DW + identity BN)
|
||||
Inference: fused into a single 3×3 DW Conv
|
||||
"""
|
||||
|
||||
def __init__(self, channels, kernel_size=3):
|
||||
super().__init__()
|
||||
self.channels = channels
|
||||
self.kernel_size = kernel_size
|
||||
padding = (kernel_size - 1) // 2
|
||||
|
||||
self.conv = Conv2D_BN(
|
||||
channels, channels, kernel_size, 1, padding, groups=channels
|
||||
)
|
||||
self.conv1 = Conv2D(
|
||||
channels, channels, 1, 1, 0, groups=channels, bias_attr=False
|
||||
)
|
||||
self.bn = BatchNorm2D(channels)
|
||||
Constant(1.0)(self.bn.weight)
|
||||
Constant(0.0)(self.bn.bias)
|
||||
|
||||
self.is_repped = False
|
||||
self.reparam_conv = None
|
||||
|
||||
def forward(self, x):
|
||||
if self.is_repped:
|
||||
return self.reparam_conv(x)
|
||||
return self.bn(self.conv(x) + self.conv1(x) + x)
|
||||
|
||||
def rep(self, fuse_lab=None):
|
||||
if self.is_repped:
|
||||
return
|
||||
fused = self._fuse_conv()
|
||||
padding = (self.kernel_size - 1) // 2
|
||||
self.reparam_conv = Conv2D(
|
||||
self.channels,
|
||||
self.channels,
|
||||
self.kernel_size,
|
||||
1,
|
||||
padding,
|
||||
groups=self.channels,
|
||||
)
|
||||
self.reparam_conv.weight.set_value(fused.weight)
|
||||
self.reparam_conv.bias.set_value(fused.bias)
|
||||
self.__delattr__("conv")
|
||||
self.__delattr__("conv1")
|
||||
self.__delattr__("bn")
|
||||
self.is_repped = True
|
||||
|
||||
@paddle.no_grad()
|
||||
def _fuse_conv(self):
|
||||
conv = self.conv.fuse()
|
||||
pad_size = self.kernel_size // 2
|
||||
conv1_w = F.pad(self.conv1.weight, [pad_size, pad_size, pad_size, pad_size])
|
||||
identity = F.pad(
|
||||
paddle.ones([self.conv1.weight.shape[0], self.conv1.weight.shape[1], 1, 1]),
|
||||
[pad_size, pad_size, pad_size, pad_size],
|
||||
)
|
||||
w = conv.weight + conv1_w + identity
|
||||
conv.weight.set_value(w)
|
||||
bn = self.bn
|
||||
scale = bn.weight / (bn._variance + bn._epsilon) ** 0.5
|
||||
conv.weight.set_value(conv.weight * scale[:, None, None, None])
|
||||
conv.bias.set_value(bn.bias + (conv.bias - bn._mean) * scale)
|
||||
return conv
|
||||
|
||||
def fuse(self):
|
||||
return self._fuse_conv()
|
||||
|
||||
|
||||
class LCNetV4Block(nn.Layer):
|
||||
"""LCNetV4 block for detection and recognition.
|
||||
|
||||
Token mixer: RepDWConv when stride=1 and in==out, else plain Conv2D_BN DW conv.
|
||||
Channel mixer: expand → act → compress (+ residual when stride=1 and in==out)
|
||||
rep() fuses all Conv2D_BN layers (mathematically exact, no accuracy change).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
stride,
|
||||
dw_size,
|
||||
use_se=False,
|
||||
lr_mult=1.0,
|
||||
expand_ratio=2,
|
||||
act_type="gelu",
|
||||
):
|
||||
super().__init__()
|
||||
self.is_repped = False
|
||||
self.has_residual = in_channels == out_channels and stride == 1
|
||||
self.use_rep_dw = stride == 1 and in_channels == out_channels
|
||||
|
||||
self.token_mixer = nn.Sequential()
|
||||
if self.use_rep_dw:
|
||||
self.token_mixer.add_sublayer("rep_dw", RepDWConv(in_channels, dw_size))
|
||||
else:
|
||||
padding = (dw_size - 1) // 2
|
||||
self.token_mixer.add_sublayer(
|
||||
"dw_conv",
|
||||
Conv2D_BN(
|
||||
in_channels,
|
||||
in_channels,
|
||||
dw_size,
|
||||
stride,
|
||||
padding,
|
||||
groups=in_channels,
|
||||
),
|
||||
)
|
||||
if use_se:
|
||||
self.token_mixer.add_sublayer("se", SELayer(in_channels, lr_mult=lr_mult))
|
||||
|
||||
hidden_channels = int(in_channels * expand_ratio)
|
||||
compress_bn_init = 0.0 if self.has_residual else 1.0
|
||||
self.channel_mixer = nn.Sequential()
|
||||
self.channel_mixer.add_sublayer(
|
||||
"expand", Conv2D_BN(in_channels, hidden_channels, 1, 1, 0)
|
||||
)
|
||||
if act_type == "gelu":
|
||||
self.channel_mixer.add_sublayer("act", GELU())
|
||||
elif act_type == "hswish":
|
||||
self.channel_mixer.add_sublayer("act", Hardswish())
|
||||
elif act_type == "relu":
|
||||
self.channel_mixer.add_sublayer("act", ReLU())
|
||||
self.channel_mixer.add_sublayer(
|
||||
"compress",
|
||||
Conv2D_BN(
|
||||
hidden_channels, out_channels, 1, 1, 0, bn_weight_init=compress_bn_init
|
||||
),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.token_mixer(x)
|
||||
if self.has_residual:
|
||||
return x + self.channel_mixer(x)
|
||||
return self.channel_mixer(x)
|
||||
|
||||
def rep(self, fuse_lab=None):
|
||||
if self.is_repped:
|
||||
return
|
||||
if self.use_rep_dw:
|
||||
self.token_mixer.rep_dw.rep(fuse_lab=fuse_lab)
|
||||
else:
|
||||
self.token_mixer.dw_conv = self.token_mixer.dw_conv.fuse()
|
||||
for name in ("expand", "compress"):
|
||||
m = getattr(self.channel_mixer, name, None)
|
||||
if isinstance(m, Conv2D_BN):
|
||||
setattr(self.channel_mixer, name, m.fuse())
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class PPLCNetV4(nn.Layer):
|
||||
"""Unified PPLCNetV4 backbone for text detection and recognition.
|
||||
|
||||
Detection (det=True):
|
||||
model_size in {'tiny', 'small', 'medium'} — see NET_CONFIG_DET.
|
||||
Returns 4-level feature list [s1_out, s2_out, s3_out, s4_out].
|
||||
|
||||
Recognition (det=False):
|
||||
model_size in {'tiny', 'small', 'base'} — see NET_CONFIG_REC.
|
||||
Returns pooled feature tensor [B, C, 1, W].
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
det=False,
|
||||
model_size="small",
|
||||
in_channels=3,
|
||||
lr_mult_list=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.det = det
|
||||
self.is_repped = False
|
||||
|
||||
if det:
|
||||
assert (
|
||||
model_size in NET_CONFIG_DET
|
||||
), "det model_size must be one of {} but got '{}'".format(
|
||||
list(NET_CONFIG_DET.keys()), model_size
|
||||
)
|
||||
cfg = NET_CONFIG_DET[model_size]
|
||||
stem_mid, stem_out = cfg["stem"]
|
||||
self.stem = StemBlock(in_channels, stem_mid, stem_out)
|
||||
|
||||
def make_stage(key):
|
||||
return nn.Sequential(
|
||||
*[
|
||||
LCNetV4Block(in_c, out_c, s, k, se, expand_ratio=2)
|
||||
for k, in_c, out_c, s, se in cfg[key]
|
||||
]
|
||||
)
|
||||
|
||||
self.blocks_s1 = make_stage("blocks_s1")
|
||||
self.blocks_s2 = make_stage("blocks_s2")
|
||||
self.blocks_s3 = make_stage("blocks_s3")
|
||||
self.blocks_s4 = make_stage("blocks_s4")
|
||||
self.out_channels = [
|
||||
cfg["blocks_s1"][-1][2],
|
||||
cfg["blocks_s2"][-1][2],
|
||||
cfg["blocks_s3"][-1][2],
|
||||
cfg["blocks_s4"][-1][2],
|
||||
]
|
||||
|
||||
else:
|
||||
assert isinstance(lr_mult_list, (list, tuple)) and len(lr_mult_list) == 6
|
||||
assert (
|
||||
model_size in NET_CONFIG_REC
|
||||
), "rec model_size must be one of {} but got '{}'".format(
|
||||
list(NET_CONFIG_REC.keys()), model_size
|
||||
)
|
||||
self.lr_mult_list = lr_mult_list
|
||||
cfg = NET_CONFIG_REC[model_size]
|
||||
stem_mid, stem_out = cfg["stem"]
|
||||
if cfg["stem_type"] == "branch":
|
||||
self.conv1 = StemBlock(3, stem_mid, stem_out, lr_mult=lr_mult_list[0])
|
||||
else:
|
||||
self.conv1 = nn.Sequential(
|
||||
Conv2D_BN(3, stem_mid, 3, 2, 1),
|
||||
GELU(),
|
||||
Conv2D_BN(stem_mid, stem_out, 3, 2, 1),
|
||||
)
|
||||
|
||||
def make_stage(stage_name, lr_idx):
|
||||
return nn.Sequential(
|
||||
*[
|
||||
LCNetV4Block(
|
||||
in_c,
|
||||
out_c,
|
||||
s,
|
||||
k,
|
||||
se,
|
||||
lr_mult=lr_mult_list[lr_idx],
|
||||
expand_ratio=2,
|
||||
)
|
||||
for k, in_c, out_c, s, se in cfg.get(stage_name, [])
|
||||
]
|
||||
)
|
||||
|
||||
self.blocks2 = make_stage("blocks2", 1)
|
||||
self.blocks3 = make_stage("blocks3", 2)
|
||||
self.blocks4 = make_stage("blocks4", 3)
|
||||
self.blocks5 = make_stage("blocks5", 4)
|
||||
self.blocks6 = make_stage("blocks6", 5)
|
||||
|
||||
for sname in reversed(
|
||||
["blocks2", "blocks3", "blocks4", "blocks5", "blocks6"]
|
||||
):
|
||||
if cfg.get(sname):
|
||||
self.out_channels = cfg[sname][-1][2]
|
||||
break
|
||||
|
||||
def forward(self, x):
|
||||
if self.det:
|
||||
x = self.stem(x)
|
||||
o1 = self.blocks_s1(x)
|
||||
o2 = self.blocks_s2(o1)
|
||||
o3 = self.blocks_s3(o2)
|
||||
o4 = self.blocks_s4(o3)
|
||||
return [o1, o2, o3, o4]
|
||||
else:
|
||||
x = self.conv1(x)
|
||||
x = self.blocks2(x)
|
||||
x = self.blocks3(x)
|
||||
x = self.blocks4(x)
|
||||
x = self.blocks5(x)
|
||||
x = self.blocks6(x)
|
||||
if self.training:
|
||||
x = F.adaptive_avg_pool2d(x, [1, 40])
|
||||
else:
|
||||
assert x.shape[2] >= 3, f"Feature height {x.shape[2]} < pool kernel 3."
|
||||
x = F.avg_pool2d(x, [3, 2])
|
||||
return x
|
||||
|
||||
def rep(self, fuse_lab=None):
|
||||
if self.is_repped:
|
||||
return
|
||||
if self.det:
|
||||
self.stem.rep()
|
||||
for stage in [
|
||||
self.blocks_s1,
|
||||
self.blocks_s2,
|
||||
self.blocks_s3,
|
||||
self.blocks_s4,
|
||||
]:
|
||||
for block in stage:
|
||||
block.rep(fuse_lab=fuse_lab)
|
||||
else:
|
||||
if hasattr(self.conv1, "rep"):
|
||||
self.conv1.rep()
|
||||
for stage in [
|
||||
self.blocks2,
|
||||
self.blocks3,
|
||||
self.blocks4,
|
||||
self.blocks5,
|
||||
self.blocks6,
|
||||
]:
|
||||
for block in stage:
|
||||
block.rep()
|
||||
self.is_repped = True
|
||||
@@ -295,6 +295,7 @@ class RepViT(nn.Layer):
|
||||
self.out_channels = [self.cfgs[ids - 1][2] for ids in out_indices]
|
||||
else:
|
||||
self.out_channels = self.cfgs[-1][2]
|
||||
self.is_repped = False
|
||||
|
||||
def forward(self, x):
|
||||
if self.out_indices is not None:
|
||||
@@ -316,6 +317,34 @@ class RepViT(nn.Layer):
|
||||
x = nn.functional.avg_pool2d(x, [h, 2])
|
||||
return x
|
||||
|
||||
@paddle.no_grad()
|
||||
def rep(self):
|
||||
"""Fuse all Conv2D_BN, RepVGGDW, Residual branches for deployment."""
|
||||
if self.is_repped:
|
||||
return
|
||||
# Snapshot the list first; track replaced prefixes to skip orphaned
|
||||
# children (e.g. Conv2D_BN inside a RepVGGDW that was already fused).
|
||||
fusable = [
|
||||
(name, sublayer)
|
||||
for name, sublayer in self.named_sublayers()
|
||||
if isinstance(sublayer, (Conv2D_BN, RepVGGDW, Residual))
|
||||
]
|
||||
replaced_prefixes = []
|
||||
for name, sublayer in fusable:
|
||||
if any(name.startswith(pfx + ".") for pfx in replaced_prefixes):
|
||||
continue
|
||||
parts = name.rsplit(".", 1)
|
||||
if len(parts) == 2:
|
||||
parent = self
|
||||
for p in parts[0].split("."):
|
||||
parent = getattr(parent, p)
|
||||
fused = sublayer.fuse()
|
||||
setattr(parent, parts[1], fused)
|
||||
# Only skip children when the module was truly replaced
|
||||
if fused is not sublayer:
|
||||
replaced_prefixes.append(name)
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
def RepSVTR(in_channels=3):
|
||||
"""
|
||||
|
||||
@@ -74,6 +74,7 @@ class Head(nn.Layer):
|
||||
)
|
||||
|
||||
self.fix_nan = fix_nan
|
||||
self.is_repped = False
|
||||
|
||||
def forward(self, x, return_f=False):
|
||||
x = self.conv1(x)
|
||||
@@ -92,6 +93,77 @@ class Head(nn.Layer):
|
||||
return x, f
|
||||
return x
|
||||
|
||||
@paddle.no_grad()
|
||||
def rep(self):
|
||||
"""Fuse Conv+BN and ConvTranspose+BN pairs for deployment."""
|
||||
if self.is_repped:
|
||||
return
|
||||
|
||||
# conv1 (Conv2D, no bias) + conv_bn1 (BatchNorm, act=relu)
|
||||
self.conv1 = self._fuse_conv_bn(self.conv1, self.conv_bn1)
|
||||
self.conv_bn1 = nn.ReLU()
|
||||
|
||||
# conv2 (Conv2DTranspose, has bias) + conv_bn2 (BatchNorm, act=relu)
|
||||
self.conv2 = self._fuse_convtranspose_bn(self.conv2, self.conv_bn2)
|
||||
self.conv_bn2 = nn.ReLU()
|
||||
|
||||
self.is_repped = True
|
||||
|
||||
@staticmethod
|
||||
@paddle.no_grad()
|
||||
def _fuse_conv_bn(conv, bn):
|
||||
"""Fuse Conv2D + BatchNorm into Conv2D with bias."""
|
||||
gamma = bn.weight
|
||||
std = paddle.sqrt(bn._variance + bn._epsilon)
|
||||
scale = gamma / std
|
||||
|
||||
w = conv.weight * scale[:, None, None, None]
|
||||
b = bn.bias - bn._mean * scale
|
||||
|
||||
fused = nn.Conv2D(
|
||||
conv._in_channels,
|
||||
conv._out_channels,
|
||||
conv._kernel_size,
|
||||
stride=conv._stride,
|
||||
padding=conv._padding,
|
||||
dilation=conv._dilation,
|
||||
groups=conv._groups,
|
||||
)
|
||||
fused.weight.set_value(w)
|
||||
fused.bias.set_value(b)
|
||||
return fused
|
||||
|
||||
@staticmethod
|
||||
@paddle.no_grad()
|
||||
def _fuse_convtranspose_bn(conv, bn):
|
||||
"""Fuse Conv2DTranspose + BatchNorm into Conv2DTranspose with bias.
|
||||
|
||||
Conv2DTranspose weight shape: [in_ch, out_ch/groups, kH, kW]
|
||||
BN scale applies on out_ch, i.e. axis=1.
|
||||
"""
|
||||
gamma = bn.weight
|
||||
std = paddle.sqrt(bn._variance + bn._epsilon)
|
||||
scale = gamma / std
|
||||
|
||||
# axis=1 for ConvTranspose (output channel dimension)
|
||||
w = conv.weight * scale[None, :, None, None]
|
||||
b = bn.bias - bn._mean * scale
|
||||
if conv.bias is not None:
|
||||
b = b + conv.bias * scale
|
||||
|
||||
fused = nn.Conv2DTranspose(
|
||||
conv._in_channels,
|
||||
conv._out_channels,
|
||||
conv._kernel_size,
|
||||
stride=conv._stride,
|
||||
padding=conv._padding,
|
||||
dilation=conv._dilation,
|
||||
groups=conv._groups,
|
||||
)
|
||||
fused.weight.set_value(w)
|
||||
fused.bias.set_value(b)
|
||||
return fused
|
||||
|
||||
|
||||
class DBHead(nn.Layer):
|
||||
"""
|
||||
@@ -101,24 +173,76 @@ class DBHead(nn.Layer):
|
||||
params(dict): super parameters for build DB network
|
||||
"""
|
||||
|
||||
def __init__(self, in_channels, k=50, **kwargs):
|
||||
def __init__(self, in_channels, k=50, aux_in_channels=0, **kwargs):
|
||||
super(DBHead, self).__init__()
|
||||
self.k = k
|
||||
self.is_repped = False
|
||||
self.binarize = Head(in_channels, **kwargs)
|
||||
self.thresh = Head(in_channels, **kwargs)
|
||||
self.aux_in_channels = aux_in_channels
|
||||
|
||||
if aux_in_channels > 0:
|
||||
self._aux_upsample_scale = {
|
||||
"aux_p4": 4, # 1/16 -> 1/4
|
||||
"aux_p3": 2, # 1/8 -> 1/4
|
||||
"aux_p2": 1, # 1/4 -> 1/4 (no-op)
|
||||
}
|
||||
# Create independent binarize + thresh Head pairs for each scale
|
||||
self.aux_binarize_p4 = Head(aux_in_channels, **kwargs)
|
||||
self.aux_thresh_p4 = Head(aux_in_channels, **kwargs)
|
||||
self.aux_binarize_p3 = Head(aux_in_channels, **kwargs)
|
||||
self.aux_thresh_p3 = Head(aux_in_channels, **kwargs)
|
||||
self.aux_binarize_p2 = Head(aux_in_channels, **kwargs)
|
||||
self.aux_thresh_p2 = Head(aux_in_channels, **kwargs)
|
||||
|
||||
def step_function(self, x, y):
|
||||
return paddle.reciprocal(1 + paddle.exp(-self.k * (x - y)))
|
||||
|
||||
def forward(self, x, targets=None):
|
||||
shrink_maps = self.binarize(x)
|
||||
# Compatible with neck returning dict (training) or tensor (inference)
|
||||
if isinstance(x, dict):
|
||||
fuse = x["fuse"]
|
||||
aux_feats = {k: x[k] for k in ("aux_p4", "aux_p3", "aux_p2") if k in x}
|
||||
else:
|
||||
fuse = x
|
||||
aux_feats = {}
|
||||
|
||||
shrink_maps = self.binarize(fuse)
|
||||
if not self.training:
|
||||
return {"maps": shrink_maps}
|
||||
|
||||
threshold_maps = self.thresh(x)
|
||||
threshold_maps = self.thresh(fuse)
|
||||
binary_maps = self.step_function(shrink_maps, threshold_maps)
|
||||
y = paddle.concat([shrink_maps, threshold_maps, binary_maps], axis=1)
|
||||
return {"maps": y}
|
||||
result = {"maps": y}
|
||||
|
||||
if self.aux_in_channels > 0 and aux_feats:
|
||||
for key, feat in aux_feats.items():
|
||||
scale = self._aux_upsample_scale[key]
|
||||
if scale > 1:
|
||||
feat = F.interpolate(
|
||||
feat, scale_factor=scale, mode="bilinear", align_corners=False
|
||||
)
|
||||
level = key[4:] # 'p4', 'p3', 'p2'
|
||||
aux_binarize = getattr(self, "aux_binarize_" + level)
|
||||
aux_thresh_head = getattr(self, "aux_thresh_" + level)
|
||||
aux_shrink = aux_binarize(feat)
|
||||
aux_thresh = aux_thresh_head(feat)
|
||||
aux_binary = self.step_function(aux_shrink, aux_thresh)
|
||||
result["aux_maps_" + level] = paddle.concat(
|
||||
[aux_shrink, aux_thresh, aux_binary], axis=1
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
def rep(self):
|
||||
"""Fuse reparam structures in all sub-modules for deployment."""
|
||||
if self.is_repped:
|
||||
return
|
||||
for layer in self.sublayers():
|
||||
if isinstance(layer, Head):
|
||||
layer.rep()
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class LocalModule(nn.Layer):
|
||||
|
||||
@@ -40,9 +40,32 @@ class CTCHead(nn.Layer):
|
||||
fc_decay=0.0004,
|
||||
mid_channels=None,
|
||||
return_feats=False,
|
||||
use_guide=False,
|
||||
**kwargs,
|
||||
):
|
||||
super(CTCHead, self).__init__()
|
||||
self.use_guide = use_guide
|
||||
if use_guide:
|
||||
self.guide_layer = nn.Sequential(
|
||||
nn.Conv1D(
|
||||
in_channels,
|
||||
in_channels,
|
||||
kernel_size=5,
|
||||
padding=2,
|
||||
groups=in_channels,
|
||||
bias_attr=False,
|
||||
),
|
||||
nn.BatchNorm1D(in_channels),
|
||||
nn.Hardswish(),
|
||||
nn.Conv1D(
|
||||
in_channels,
|
||||
in_channels,
|
||||
kernel_size=1,
|
||||
bias_attr=False,
|
||||
),
|
||||
nn.BatchNorm1D(in_channels),
|
||||
nn.Hardswish(),
|
||||
)
|
||||
if mid_channels is None:
|
||||
weight_attr, bias_attr = get_para_bias_attr(
|
||||
l2_decay=fc_decay, k=in_channels
|
||||
@@ -75,6 +98,11 @@ class CTCHead(nn.Layer):
|
||||
self.return_feats = return_feats
|
||||
|
||||
def forward(self, x, targets=None):
|
||||
if self.use_guide:
|
||||
x = x.transpose([0, 2, 1])
|
||||
x = self.guide_layer(x)
|
||||
x = x.transpose([0, 2, 1])
|
||||
|
||||
if self.mid_channels is None:
|
||||
predicts = self.fc(x)
|
||||
else:
|
||||
|
||||
@@ -16,7 +16,7 @@ __all__ = ["build_neck"]
|
||||
|
||||
|
||||
def build_neck(config):
|
||||
from .db_fpn import DBFPN, RSEFPN, LKPAN
|
||||
from .db_fpn import DBFPN, RSEFPN, RepLKFPN, LKPAN, RepLKPAN
|
||||
from .east_fpn import EASTFPN
|
||||
from .sast_fpn import SASTFPN
|
||||
from .rnn import SequenceEncoder
|
||||
@@ -34,8 +34,10 @@ def build_neck(config):
|
||||
"FPN",
|
||||
"FCEFPN",
|
||||
"LKPAN",
|
||||
"RepLKPAN",
|
||||
"DBFPN",
|
||||
"RSEFPN",
|
||||
"RepLKFPN",
|
||||
"EASTFPN",
|
||||
"SASTFPN",
|
||||
"SequenceEncoder",
|
||||
|
||||
@@ -304,6 +304,131 @@ class RSEFPN(nn.Layer):
|
||||
return fuse
|
||||
|
||||
|
||||
class RepLKFPN(nn.Layer):
|
||||
"""Optimized RSEFPN: replaces 3x3 standard Conv in inp_conv with
|
||||
DilatedReparamBlock (DW, 5x5) + PWConv 1x1 + SE.
|
||||
|
||||
Uses the existing DilatedReparamBlock from UniRepLKNet to provide
|
||||
multi-branch dilated training with single-conv inference.
|
||||
|
||||
Changes vs RSEFPN:
|
||||
- inp_conv: RSELayer(3x3 std Conv + SE)
|
||||
→ DilatedReparamBlock(5x5 DW) + PWConv(1x1) + SE
|
||||
- ins_conv: unchanged (1x1 Conv, no benefit from DW decomposition)
|
||||
|
||||
Parameter comparison (out_channels=96, 4 levels):
|
||||
RSEFPN inp_conv: 4 × (96×24×9 + SE) = 4 × 21,054 = 84,216
|
||||
RepLKFPN inp_conv: 4 × (DilReparam96 + 96×24 + SE)
|
||||
= 4 × (96×25 + 96×2 + 2×(96×9+96×2) + 96×24 + SE)
|
||||
= 4 × (2,400 + 192 + 2×(864+192) + 2,304 + 318)
|
||||
= 4 × 7,326 = 29,304
|
||||
inp_conv reduction: 65.2%
|
||||
Receptive field: 3×3 → 5×5 (with multi-dilation 3,5 patterns in training)
|
||||
|
||||
Inference: DilatedReparamBlock merges to single 5x5 DWConv, zero extra cost.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, in_channels, out_channels, shortcut=True, dilated_kernel_size=7, **kwargs
|
||||
):
|
||||
super(RepLKFPN, self).__init__()
|
||||
self.out_channels = out_channels
|
||||
self.is_repped = False
|
||||
self.ins_conv = nn.LayerList()
|
||||
self.inp_conv_dw = nn.LayerList()
|
||||
self.inp_conv_pw = nn.LayerList()
|
||||
self.inp_conv_se = nn.LayerList()
|
||||
self.shortcut = shortcut
|
||||
|
||||
self.intracl = False
|
||||
if "intracl" in kwargs.keys() and kwargs["intracl"] is True:
|
||||
self.intracl = kwargs["intracl"]
|
||||
self.incl1 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
self.incl2 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
self.incl3 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
self.incl4 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
|
||||
weight_attr = paddle.nn.initializer.KaimingUniform()
|
||||
|
||||
for i in range(len(in_channels)):
|
||||
self.ins_conv.append(
|
||||
RSELayer(in_channels[i], out_channels, kernel_size=1, shortcut=shortcut)
|
||||
)
|
||||
|
||||
self.inp_conv_dw.append(
|
||||
DilatedReparamBlock(
|
||||
channels=out_channels, kernel_size=dilated_kernel_size
|
||||
)
|
||||
)
|
||||
|
||||
self.inp_conv_pw.append(
|
||||
nn.Conv2D(
|
||||
in_channels=out_channels,
|
||||
out_channels=out_channels // 4,
|
||||
kernel_size=1,
|
||||
weight_attr=ParamAttr(initializer=weight_attr),
|
||||
bias_attr=False,
|
||||
)
|
||||
)
|
||||
|
||||
self.inp_conv_se.append(SEModule(out_channels // 4))
|
||||
|
||||
def _inp_forward(self, x, idx):
|
||||
x = self.inp_conv_dw[idx](x)
|
||||
x = self.inp_conv_pw[idx](x)
|
||||
if self.shortcut:
|
||||
x = x + self.inp_conv_se[idx](x)
|
||||
else:
|
||||
x = self.inp_conv_se[idx](x)
|
||||
return x
|
||||
|
||||
def forward(self, x):
|
||||
c2, c3, c4, c5 = x
|
||||
|
||||
in5 = self.ins_conv[3](c5)
|
||||
in4 = self.ins_conv[2](c4)
|
||||
in3 = self.ins_conv[1](c3)
|
||||
in2 = self.ins_conv[0](c2)
|
||||
|
||||
out4 = in4 + F.upsample(
|
||||
in5, scale_factor=2, mode="nearest", align_mode=1
|
||||
) # 1/16
|
||||
out3 = in3 + F.upsample(
|
||||
out4, scale_factor=2, mode="nearest", align_mode=1
|
||||
) # 1/8
|
||||
out2 = in2 + F.upsample(
|
||||
out3, scale_factor=2, mode="nearest", align_mode=1
|
||||
) # 1/4
|
||||
|
||||
p5 = self._inp_forward(in5, 3)
|
||||
p4 = self._inp_forward(out4, 2)
|
||||
p3 = self._inp_forward(out3, 1)
|
||||
p2 = self._inp_forward(out2, 0)
|
||||
|
||||
if self.intracl is True:
|
||||
p5 = self.incl4(p5)
|
||||
p4 = self.incl3(p4)
|
||||
p3 = self.incl2(p3)
|
||||
p2 = self.incl1(p2)
|
||||
|
||||
p5 = F.upsample(p5, scale_factor=8, mode="nearest", align_mode=1)
|
||||
p4 = F.upsample(p4, scale_factor=4, mode="nearest", align_mode=1)
|
||||
p3 = F.upsample(p3, scale_factor=2, mode="nearest", align_mode=1)
|
||||
|
||||
fuse = paddle.concat([p5, p4, p3, p2], axis=1)
|
||||
if self.training:
|
||||
return {"fuse": fuse, "aux_p4": out4, "aux_p3": out3, "aux_p2": out2}
|
||||
return fuse
|
||||
|
||||
def rep(self):
|
||||
"""Merge DilatedReparamBlock branches for inference deployment."""
|
||||
if self.is_repped:
|
||||
return
|
||||
for i in range(len(self.inp_conv_dw)):
|
||||
self.inp_conv_dw[i].rep()
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class LKPAN(nn.Layer):
|
||||
def __init__(self, in_channels, out_channels, mode="large", **kwargs):
|
||||
super(LKPAN, self).__init__()
|
||||
@@ -426,6 +551,407 @@ class LKPAN(nn.Layer):
|
||||
return fuse
|
||||
|
||||
|
||||
class DilatedReparamBlock(nn.Layer):
|
||||
"""
|
||||
Dilated Reparam Block from UniRepLKNet.
|
||||
Reference: https://github.com/AILab-CVC/UniRepLKNet
|
||||
|
||||
Training: uses multiple parallel dilated depthwise convolutions + BN
|
||||
Inference: all branches merge into a single large-kernel depthwise conv
|
||||
|
||||
For kernel_size=9, the branches are:
|
||||
- origin: 9x9 DW Conv (dil=1)
|
||||
- branch1: 5x5 DW Conv (dil=1, equiv RF=5)
|
||||
- branch2: 5x5 DW Conv (dil=2, equiv RF=9)
|
||||
- branch3: 3x3 DW Conv (dil=3, equiv RF=7)
|
||||
- branch4: 3x3 DW Conv (dil=4, equiv RF=9)
|
||||
"""
|
||||
|
||||
def __init__(self, channels, kernel_size=9, deploy=False):
|
||||
super(DilatedReparamBlock, self).__init__()
|
||||
self.channels = channels
|
||||
self.kernel_size = kernel_size
|
||||
self.is_repped = deploy
|
||||
|
||||
if kernel_size == 9:
|
||||
self.kernel_sizes = [5, 5, 3, 3]
|
||||
self.dilates = [1, 2, 3, 4]
|
||||
elif kernel_size == 7:
|
||||
self.kernel_sizes = [5, 3, 3]
|
||||
self.dilates = [1, 2, 3]
|
||||
elif kernel_size == 5:
|
||||
self.kernel_sizes = [3, 3]
|
||||
self.dilates = [1, 2]
|
||||
elif kernel_size == 11:
|
||||
self.kernel_sizes = [5, 5, 3, 3, 3]
|
||||
self.dilates = [1, 2, 3, 4, 5]
|
||||
elif kernel_size == 13:
|
||||
self.kernel_sizes = [5, 7, 3, 3, 3]
|
||||
self.dilates = [1, 2, 3, 4, 5]
|
||||
else:
|
||||
raise ValueError(
|
||||
"DilatedReparamBlock requires kernel_size in [5,7,9,11,13], "
|
||||
"but got {}".format(kernel_size)
|
||||
)
|
||||
|
||||
if not self.is_repped:
|
||||
self.lk_origin = nn.Conv2D(
|
||||
in_channels=channels,
|
||||
out_channels=channels,
|
||||
kernel_size=kernel_size,
|
||||
stride=1,
|
||||
padding=kernel_size // 2,
|
||||
groups=channels,
|
||||
bias_attr=False,
|
||||
)
|
||||
self.origin_bn = nn.BatchNorm2D(channels)
|
||||
|
||||
for k, r in zip(self.kernel_sizes, self.dilates):
|
||||
equiv_ks = r * (k - 1) + 1
|
||||
p = equiv_ks // 2
|
||||
conv = nn.Conv2D(
|
||||
in_channels=channels,
|
||||
out_channels=channels,
|
||||
kernel_size=k,
|
||||
stride=1,
|
||||
padding=p,
|
||||
dilation=r,
|
||||
groups=channels,
|
||||
bias_attr=False,
|
||||
)
|
||||
bn = nn.BatchNorm2D(channels)
|
||||
setattr(self, "dil_conv_k{}_{}".format(k, r), conv)
|
||||
setattr(self, "dil_bn_k{}_{}".format(k, r), bn)
|
||||
else:
|
||||
self.lk_origin = nn.Conv2D(
|
||||
in_channels=channels,
|
||||
out_channels=channels,
|
||||
kernel_size=kernel_size,
|
||||
stride=1,
|
||||
padding=kernel_size // 2,
|
||||
groups=channels,
|
||||
bias_attr=True,
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
if self.is_repped:
|
||||
return self.lk_origin(x)
|
||||
out = self.origin_bn(self.lk_origin(x))
|
||||
for k, r in zip(self.kernel_sizes, self.dilates):
|
||||
conv = getattr(self, "dil_conv_k{}_{}".format(k, r))
|
||||
bn = getattr(self, "dil_bn_k{}_{}".format(k, r))
|
||||
out = out + bn(conv(x))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _fuse_bn(conv, bn):
|
||||
"""Fuse Conv2D + BatchNorm2D into a single Conv2D (weight, bias)."""
|
||||
kernel = conv.weight
|
||||
gamma = bn.weight
|
||||
beta = bn.bias
|
||||
running_mean = bn._mean
|
||||
running_var = bn._variance
|
||||
eps = bn._epsilon
|
||||
std = paddle.sqrt(running_var + eps)
|
||||
fused_weight = kernel * (gamma / std).reshape([-1, 1, 1, 1])
|
||||
fused_bias = beta - running_mean * gamma / std
|
||||
return fused_weight, fused_bias
|
||||
|
||||
@staticmethod
|
||||
def _convert_dilated_to_nondilated(kernel, dilate_rate):
|
||||
"""Convert dilated conv kernel to equivalent non-dilated (sparse) kernel
|
||||
by inserting zeros between kernel elements using transposed convolution."""
|
||||
if dilate_rate == 1:
|
||||
return kernel
|
||||
identity = paddle.ones(shape=[1, 1, 1, 1], dtype=kernel.dtype)
|
||||
# F.conv2d_transpose with stride=dilate_rate inserts zeros
|
||||
# Process each channel independently
|
||||
C = kernel.shape[0]
|
||||
result_list = []
|
||||
for i in range(C):
|
||||
k_i = kernel[i : i + 1] # (1, 1, kH, kW)
|
||||
dilated = F.conv2d_transpose(k_i, identity, stride=dilate_rate)
|
||||
result_list.append(dilated)
|
||||
return paddle.concat(result_list, axis=0)
|
||||
|
||||
@staticmethod
|
||||
def _merge_dilated_into_large_kernel(large_kernel, dilated_kernel, dilated_r):
|
||||
"""Pad dilated equivalent kernel to large kernel size and add."""
|
||||
large_k = large_kernel.shape[2]
|
||||
dilated_k = dilated_kernel.shape[2]
|
||||
equiv_ks = dilated_r * (dilated_k - 1) + 1
|
||||
equiv_kernel = DilatedReparamBlock._convert_dilated_to_nondilated(
|
||||
dilated_kernel, dilated_r
|
||||
)
|
||||
rows_to_pad = large_k // 2 - equiv_ks // 2
|
||||
if rows_to_pad > 0:
|
||||
merged = large_kernel + F.pad(
|
||||
equiv_kernel, [rows_to_pad, rows_to_pad, rows_to_pad, rows_to_pad]
|
||||
)
|
||||
else:
|
||||
merged = large_kernel + equiv_kernel
|
||||
return merged
|
||||
|
||||
@paddle.no_grad()
|
||||
def rep(self):
|
||||
"""Merge all parallel branches into a single large-kernel DW conv.
|
||||
Call this before switching to deploy/inference mode."""
|
||||
if self.is_repped:
|
||||
return
|
||||
origin_k, origin_b = self._fuse_bn(self.lk_origin, self.origin_bn)
|
||||
for k, r in zip(self.kernel_sizes, self.dilates):
|
||||
conv = getattr(self, "dil_conv_k{}_{}".format(k, r))
|
||||
bn = getattr(self, "dil_bn_k{}_{}".format(k, r))
|
||||
branch_k, branch_b = self._fuse_bn(conv, bn)
|
||||
origin_k = self._merge_dilated_into_large_kernel(origin_k, branch_k, r)
|
||||
origin_b = origin_b + branch_b
|
||||
|
||||
merged_conv = nn.Conv2D(
|
||||
in_channels=self.channels,
|
||||
out_channels=self.channels,
|
||||
kernel_size=self.kernel_size,
|
||||
stride=1,
|
||||
padding=self.kernel_size // 2,
|
||||
groups=self.channels,
|
||||
bias_attr=True,
|
||||
)
|
||||
merged_conv.weight.set_value(origin_k)
|
||||
merged_conv.bias.set_value(origin_b)
|
||||
self.lk_origin = merged_conv
|
||||
self.is_repped = True
|
||||
|
||||
delattr(self, "origin_bn")
|
||||
for k, r in zip(self.kernel_sizes, self.dilates):
|
||||
delattr(self, "dil_conv_k{}_{}".format(k, r))
|
||||
delattr(self, "dil_bn_k{}_{}".format(k, r))
|
||||
|
||||
|
||||
class DilatedReparamConv(nn.Layer):
|
||||
"""
|
||||
A drop-in replacement for standard Conv2D (in_ch → out_ch, large kernel)
|
||||
using DilatedReparamBlock (depthwise) + 1x1 pointwise convolution.
|
||||
|
||||
Architecture:
|
||||
input(in_ch) → DilatedReparamBlock(in_ch, DW, kernel_size) → 1x1 Conv(in_ch→out_ch) → BN
|
||||
|
||||
This decomposition replaces a single large standard conv with DW + PW,
|
||||
drastically reducing parameters while maintaining the large receptive field.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, in_channels, out_channels, kernel_size=9, deploy=False, **kwargs
|
||||
):
|
||||
super(DilatedReparamConv, self).__init__()
|
||||
self.is_repped = False
|
||||
weight_attr = paddle.nn.initializer.KaimingUniform()
|
||||
self.dw = DilatedReparamBlock(
|
||||
channels=in_channels, kernel_size=kernel_size, deploy=deploy
|
||||
)
|
||||
self.pw = nn.Conv2D(
|
||||
in_channels=in_channels,
|
||||
out_channels=out_channels,
|
||||
kernel_size=1,
|
||||
weight_attr=ParamAttr(initializer=weight_attr),
|
||||
bias_attr=False,
|
||||
)
|
||||
self.bn = nn.BatchNorm2D(out_channels)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.dw(x)
|
||||
x = self.pw(x)
|
||||
if not self.is_repped:
|
||||
x = self.bn(x)
|
||||
return x
|
||||
|
||||
@paddle.no_grad()
|
||||
def rep(self):
|
||||
"""Fuse DW branches + PW Conv + BN for deployment."""
|
||||
if self.is_repped:
|
||||
return
|
||||
self.dw.rep()
|
||||
# Fuse pw(Conv2D, no bias) + bn(BatchNorm2D) into single Conv2D with bias
|
||||
conv, bn = self.pw, self.bn
|
||||
gamma = bn.weight
|
||||
std = paddle.sqrt(bn._variance + bn._epsilon)
|
||||
scale = gamma / std
|
||||
w = conv.weight * scale[:, None, None, None]
|
||||
b = bn.bias - bn._mean * scale
|
||||
fused = nn.Conv2D(
|
||||
conv._in_channels,
|
||||
conv._out_channels,
|
||||
conv._kernel_size,
|
||||
stride=conv._stride,
|
||||
padding=conv._padding,
|
||||
dilation=conv._dilation,
|
||||
groups=conv._groups,
|
||||
)
|
||||
fused.weight.set_value(w)
|
||||
fused.bias.set_value(b)
|
||||
self.pw = fused
|
||||
del self.bn
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class RepLKPAN(nn.Layer):
|
||||
"""
|
||||
Optimized LKPAN using UniRepLKNet's DilatedReparamBlock.
|
||||
|
||||
Replaces the 8 standard 9x9 Conv2D in LKPAN (4 inp_conv + 4 pan_lat_conv)
|
||||
with DilatedReparamConv (DW large-kernel reparam + 1x1 pointwise).
|
||||
|
||||
Parameter comparison (out_channels=256, i.e. inner_ch=64):
|
||||
┌──────────────────────────────────────────────────────────────────────────┐
|
||||
│ Component │ Original (Std 9x9 Conv) │ UniRepLK (DW+PW) │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ inp_conv[i]: │ 256×64×9×9 = 1,327,104 │ DW: 256×1×9×9 = 20,736 │
|
||||
│ (256→64, ×4) │ │ +4 dilated DW branches │
|
||||
│ │ │ ≈ 256×(25+25+9+9) │
|
||||
│ │ │ = 17,408 (training) │
|
||||
│ │ │ PW: 256×64×1×1 = 16,384 │
|
||||
│ │ │ BN: 64×2 = 128 │
|
||||
│ │ │ Subtotal/layer ≈ 54,656 │
|
||||
│ │ │ (vs 1,327,104 original) │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ pan_lat_conv[i]: │ 64×64×9×9 = 331,776 │ DW: 64×1×9×9 = 5,184 │
|
||||
│ (64→64, ×4) │ │ +4 dilated DW branches │
|
||||
│ │ │ ≈ 64×(25+25+9+9) │
|
||||
│ │ │ = 4,352 (training) │
|
||||
│ │ │ PW: 64×64×1×1 = 4,096 │
|
||||
│ │ │ BN: 64×2 = 128 │
|
||||
│ │ │ Subtotal/layer ≈ 13,760 │
|
||||
│ │ │ (vs 331,776 original) │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ Total 9x9 params │ 4×1,327,104 + 4×331,776 │ 4×54,656 + 4×13,760 │
|
||||
│ (8 layers) │ = 6,635,520 │ = 273,664 │
|
||||
│ │ │ 95.9% reduction │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ Inference(reparam)│ Same as above │ DW 9x9 merged (no extra │
|
||||
│ │ │ branch overhead)+PW 1x1 │
|
||||
│ │ │ FLOPs also greatly reduced│
|
||||
└──────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Note: BN params in dilated branches are only present during training and
|
||||
merged into the DW conv weights at inference. The training param count
|
||||
includes these BN params; inference param count is slightly lower.
|
||||
"""
|
||||
|
||||
def __init__(self, in_channels, out_channels, mode="large", **kwargs):
|
||||
super(RepLKPAN, self).__init__()
|
||||
self.out_channels = out_channels
|
||||
self.is_repped = False
|
||||
weight_attr = paddle.nn.initializer.KaimingUniform()
|
||||
|
||||
self.ins_conv = nn.LayerList()
|
||||
self.inp_conv = nn.LayerList()
|
||||
# pan head
|
||||
self.pan_head_conv = nn.LayerList()
|
||||
self.pan_lat_conv = nn.LayerList()
|
||||
|
||||
for i in range(len(in_channels)):
|
||||
self.ins_conv.append(
|
||||
nn.Conv2D(
|
||||
in_channels=in_channels[i],
|
||||
out_channels=self.out_channels,
|
||||
kernel_size=1,
|
||||
weight_attr=ParamAttr(initializer=weight_attr),
|
||||
bias_attr=False,
|
||||
)
|
||||
)
|
||||
|
||||
self.inp_conv.append(
|
||||
DilatedReparamConv(
|
||||
in_channels=self.out_channels,
|
||||
out_channels=self.out_channels // 4,
|
||||
kernel_size=9,
|
||||
)
|
||||
)
|
||||
|
||||
if i > 0:
|
||||
self.pan_head_conv.append(
|
||||
nn.Conv2D(
|
||||
in_channels=self.out_channels // 4,
|
||||
out_channels=self.out_channels // 4,
|
||||
kernel_size=3,
|
||||
padding=1,
|
||||
stride=2,
|
||||
weight_attr=ParamAttr(initializer=weight_attr),
|
||||
bias_attr=False,
|
||||
)
|
||||
)
|
||||
self.pan_lat_conv.append(
|
||||
DilatedReparamConv(
|
||||
in_channels=self.out_channels // 4,
|
||||
out_channels=self.out_channels // 4,
|
||||
kernel_size=9,
|
||||
)
|
||||
)
|
||||
|
||||
self.intracl = False
|
||||
if "intracl" in kwargs.keys() and kwargs["intracl"] is True:
|
||||
self.intracl = kwargs["intracl"]
|
||||
self.incl1 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
self.incl2 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
self.incl3 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
self.incl4 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)
|
||||
|
||||
def forward(self, x):
|
||||
c2, c3, c4, c5 = x
|
||||
|
||||
in5 = self.ins_conv[3](c5)
|
||||
in4 = self.ins_conv[2](c4)
|
||||
in3 = self.ins_conv[1](c3)
|
||||
in2 = self.ins_conv[0](c2)
|
||||
|
||||
out4 = in4 + F.upsample(
|
||||
in5, scale_factor=2, mode="nearest", align_mode=1
|
||||
) # 1/16
|
||||
out3 = in3 + F.upsample(
|
||||
out4, scale_factor=2, mode="nearest", align_mode=1
|
||||
) # 1/8
|
||||
out2 = in2 + F.upsample(
|
||||
out3, scale_factor=2, mode="nearest", align_mode=1
|
||||
) # 1/4
|
||||
|
||||
f5 = self.inp_conv[3](in5)
|
||||
f4 = self.inp_conv[2](out4)
|
||||
f3 = self.inp_conv[1](out3)
|
||||
f2 = self.inp_conv[0](out2)
|
||||
|
||||
pan3 = f3 + self.pan_head_conv[0](f2)
|
||||
pan4 = f4 + self.pan_head_conv[1](pan3)
|
||||
pan5 = f5 + self.pan_head_conv[2](pan4)
|
||||
|
||||
p2 = self.pan_lat_conv[0](f2)
|
||||
p3 = self.pan_lat_conv[1](pan3)
|
||||
p4 = self.pan_lat_conv[2](pan4)
|
||||
p5 = self.pan_lat_conv[3](pan5)
|
||||
|
||||
if self.intracl is True:
|
||||
p5 = self.incl4(p5)
|
||||
p4 = self.incl3(p4)
|
||||
p3 = self.incl2(p3)
|
||||
p2 = self.incl1(p2)
|
||||
|
||||
p5 = F.upsample(p5, scale_factor=8, mode="nearest", align_mode=1)
|
||||
p4 = F.upsample(p4, scale_factor=4, mode="nearest", align_mode=1)
|
||||
p3 = F.upsample(p3, scale_factor=2, mode="nearest", align_mode=1)
|
||||
|
||||
fuse = paddle.concat([p5, p4, p3, p2], axis=1)
|
||||
if self.training:
|
||||
return {"fuse": fuse, "aux_p4": out4, "aux_p3": out3, "aux_p2": out2}
|
||||
return fuse
|
||||
|
||||
def rep(self):
|
||||
"""Merge all DilatedReparamBlock branches and fuse PW+BN for deployment."""
|
||||
if self.is_repped:
|
||||
return
|
||||
for i in range(len(self.inp_conv)):
|
||||
self.inp_conv[i].rep()
|
||||
for i in range(len(self.pan_lat_conv)):
|
||||
self.pan_lat_conv[i].rep()
|
||||
self.is_repped = True
|
||||
|
||||
|
||||
class ASFBlock(nn.Layer):
|
||||
"""
|
||||
This code is referred from:
|
||||
|
||||
+110
-2
@@ -18,6 +18,7 @@ from __future__ import print_function
|
||||
|
||||
import paddle
|
||||
from paddle import nn
|
||||
from paddle.nn.initializer import KaimingNormal
|
||||
|
||||
from ppocr.modeling.heads.rec_ctc_head import get_para_bias_attr
|
||||
from ppocr.modeling.backbones.rec_svtrnet import (
|
||||
@@ -238,6 +239,112 @@ class EncoderWithSVTR(nn.Layer):
|
||||
return z
|
||||
|
||||
|
||||
class EncoderWithLightSVTR(nn.Layer):
|
||||
"""Light SVTR neck: attention with lightweight skip connection.
|
||||
|
||||
Replaces heavy guide fusion with a lightweight 1x1 skip conv + add.
|
||||
Adds a DWConv before attention for local context priming.
|
||||
|
||||
When use_guide=True, applies stop_gradient to input so that neck
|
||||
gradients do not propagate back to the backbone (implicit regularization).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
dims=64,
|
||||
depth=1,
|
||||
num_heads=8,
|
||||
qkv_bias=True,
|
||||
mlp_ratio=4.0,
|
||||
drop_rate=0.1,
|
||||
attn_drop_rate=0.1,
|
||||
drop_path=0.0,
|
||||
qk_scale=None,
|
||||
local_kernel=7,
|
||||
use_guide=False,
|
||||
):
|
||||
super().__init__()
|
||||
self.use_guide = use_guide
|
||||
self.conv_reduce = ConvBNLayer(
|
||||
in_channels,
|
||||
dims,
|
||||
kernel_size=1,
|
||||
act=nn.Swish,
|
||||
)
|
||||
self.local_conv = nn.Sequential(
|
||||
nn.Conv2D(
|
||||
dims,
|
||||
dims,
|
||||
[1, local_kernel],
|
||||
padding=[0, local_kernel // 2],
|
||||
groups=dims,
|
||||
bias_attr=False,
|
||||
weight_attr=paddle.ParamAttr(initializer=KaimingNormal()),
|
||||
),
|
||||
nn.BatchNorm2D(dims),
|
||||
nn.Swish(),
|
||||
)
|
||||
|
||||
self.svtr_block = nn.LayerList(
|
||||
[
|
||||
Block(
|
||||
dim=dims,
|
||||
num_heads=num_heads,
|
||||
mixer="Global",
|
||||
HW=None,
|
||||
mlp_ratio=mlp_ratio,
|
||||
qkv_bias=qkv_bias,
|
||||
qk_scale=qk_scale,
|
||||
drop=drop_rate,
|
||||
act_layer=nn.Swish,
|
||||
attn_drop=attn_drop_rate,
|
||||
drop_path=drop_path,
|
||||
norm_layer="nn.LayerNorm",
|
||||
epsilon=1e-05,
|
||||
prenorm=False,
|
||||
)
|
||||
for _ in range(depth)
|
||||
]
|
||||
)
|
||||
self.norm = nn.LayerNorm(dims, epsilon=1e-6)
|
||||
|
||||
self.skip_conv = ConvBNLayer(
|
||||
in_channels,
|
||||
dims,
|
||||
kernel_size=1,
|
||||
act=nn.Swish,
|
||||
)
|
||||
|
||||
self.out_channels = dims
|
||||
self.apply(self._init_weights)
|
||||
|
||||
def _init_weights(self, m):
|
||||
if isinstance(m, nn.Linear):
|
||||
trunc_normal_(m.weight)
|
||||
if m.bias is not None:
|
||||
zeros_(m.bias)
|
||||
elif isinstance(m, nn.LayerNorm):
|
||||
zeros_(m.bias)
|
||||
ones_(m.weight)
|
||||
|
||||
def forward(self, x):
|
||||
if self.use_guide:
|
||||
x = x.clone()
|
||||
x.stop_gradient = True
|
||||
skip = self.skip_conv(x)
|
||||
z = self.conv_reduce(x)
|
||||
z = z + self.local_conv(z)
|
||||
B, C, H, W = z.shape
|
||||
z = z.flatten(2).transpose([0, 2, 1])
|
||||
for blk in self.svtr_block:
|
||||
z = blk(z)
|
||||
z = self.norm(z)
|
||||
z = z.reshape([0, H, W, C]).transpose([0, 3, 1, 2])
|
||||
z = z + skip
|
||||
return z
|
||||
|
||||
|
||||
class SequenceEncoder(nn.Layer):
|
||||
def __init__(self, in_channels, encoder_type, hidden_size=48, **kwargs):
|
||||
super(SequenceEncoder, self).__init__()
|
||||
@@ -252,12 +359,13 @@ class SequenceEncoder(nn.Layer):
|
||||
"fc": EncoderWithFC,
|
||||
"rnn": EncoderWithRNN,
|
||||
"svtr": EncoderWithSVTR,
|
||||
"lightsvtr": EncoderWithLightSVTR,
|
||||
"cascadernn": EncoderWithCascadeRNN,
|
||||
}
|
||||
assert encoder_type in support_encoder_dict, "{} must in {}".format(
|
||||
encoder_type, support_encoder_dict.keys()
|
||||
)
|
||||
if encoder_type == "svtr":
|
||||
if encoder_type in ("svtr", "lightsvtr"):
|
||||
self.encoder = support_encoder_dict[encoder_type](
|
||||
self.encoder_reshape.out_channels, **kwargs
|
||||
)
|
||||
@@ -273,7 +381,7 @@ class SequenceEncoder(nn.Layer):
|
||||
self.only_reshape = False
|
||||
|
||||
def forward(self, x):
|
||||
if self.encoder_type != "svtr":
|
||||
if self.encoder_type not in ("svtr", "lightsvtr"):
|
||||
x = self.encoder_reshape(x)
|
||||
if not self.only_reshape:
|
||||
x = self.encoder(x)
|
||||
|
||||
@@ -17,11 +17,48 @@ from __future__ import division
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
import copy
|
||||
import math
|
||||
import paddle
|
||||
|
||||
__all__ = ["build_optimizer"]
|
||||
|
||||
|
||||
class CosineWeightDecayScheduler(object):
|
||||
"""Cosine-anneal the optimizer's weight decay each step.
|
||||
|
||||
wd(t) = end + 0.5 * (start - end) * (1 + cos(pi * t / T))
|
||||
|
||||
During warmup the coefficient is held at `start_factor`.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, optimizer, start_factor, end_factor, total_steps, warmup_steps=0
|
||||
):
|
||||
self.optimizer = optimizer
|
||||
self.start_factor = start_factor
|
||||
self.end_factor = end_factor
|
||||
self.total_steps = total_steps
|
||||
self.warmup_steps = warmup_steps
|
||||
self._step = 0
|
||||
|
||||
def step(self):
|
||||
self._step += 1
|
||||
if self._step <= self.warmup_steps:
|
||||
wd = self.start_factor
|
||||
else:
|
||||
progress = (self._step - self.warmup_steps) / max(
|
||||
1, self.total_steps - self.warmup_steps
|
||||
)
|
||||
progress = min(progress, 1.0)
|
||||
wd = self.end_factor + 0.5 * (self.start_factor - self.end_factor) * (
|
||||
1 + math.cos(math.pi * progress)
|
||||
)
|
||||
self.optimizer.regularization._coeff = wd
|
||||
|
||||
def get_wd(self):
|
||||
return self.optimizer.regularization._coeff
|
||||
|
||||
|
||||
def build_lr_scheduler(lr_config, epochs, step_each_epoch):
|
||||
from . import learning_rate
|
||||
|
||||
@@ -39,12 +76,26 @@ def build_optimizer(config, epochs, step_each_epoch, model):
|
||||
lr = build_lr_scheduler(config.pop("lr"), epochs, step_each_epoch)
|
||||
|
||||
# step2 build regularization
|
||||
wd_scheduler = None
|
||||
if "regularizer" in config and config["regularizer"] is not None:
|
||||
reg_config = config.pop("regularizer")
|
||||
reg_name = reg_config.pop("name")
|
||||
if not hasattr(regularizer, reg_name):
|
||||
reg_name += "Decay"
|
||||
reg = getattr(regularizer, reg_name)(**reg_config)()
|
||||
reg_obj = getattr(regularizer, reg_name)(**reg_config)
|
||||
reg = reg_obj()
|
||||
|
||||
# Build weight decay scheduler for CosineL2Decay
|
||||
if isinstance(reg_obj, regularizer.CosineL2Decay):
|
||||
warmup_epoch = reg_obj.warmup_epoch
|
||||
warmup_steps = round(warmup_epoch * step_each_epoch)
|
||||
total_steps = step_each_epoch * epochs
|
||||
wd_scheduler = {
|
||||
"start_factor": reg_obj.start_factor,
|
||||
"end_factor": reg_obj.end_factor,
|
||||
"total_steps": total_steps,
|
||||
"warmup_steps": warmup_steps,
|
||||
}
|
||||
elif "weight_decay" in config:
|
||||
reg = config.pop("weight_decay")
|
||||
else:
|
||||
@@ -63,4 +114,10 @@ def build_optimizer(config, epochs, step_each_epoch, model):
|
||||
optim = getattr(optimizer, optim_name)(
|
||||
learning_rate=lr, weight_decay=reg, grad_clip=grad_clip, **config
|
||||
)
|
||||
return optim(model), lr
|
||||
built_optim = optim(model)
|
||||
|
||||
# Instantiate the scheduler now that we have the real optimizer
|
||||
if wd_scheduler is not None:
|
||||
wd_scheduler = CosineWeightDecayScheduler(built_optim, **wd_scheduler)
|
||||
|
||||
return built_optim, lr, wd_scheduler
|
||||
@@ -49,3 +49,30 @@ class L2Decay(object):
|
||||
|
||||
def __call__(self):
|
||||
return self.coeff
|
||||
|
||||
|
||||
class CosineL2Decay(object):
|
||||
"""
|
||||
L2 Weight Decay with cosine annealing schedule.
|
||||
|
||||
Anneals the weight decay coefficient from `factor` to `end_factor`
|
||||
following a cosine curve over total training steps, with optional
|
||||
linear warmup. Avoids over-regularizing small-capacity models.
|
||||
|
||||
Reference: EfficientNetV2 (Tan & Le, 2021) - "annealing the loss
|
||||
incurred by weight decay regularization over the course of training".
|
||||
|
||||
Args:
|
||||
factor(float): initial weight decay coefficient.
|
||||
end_factor(float): final weight decay coefficient. Default: 0.0.
|
||||
warmup_epoch(int|float): warmup epochs (same as lr warmup). Default: 0.
|
||||
"""
|
||||
|
||||
def __init__(self, factor=5e-5, end_factor=0.0, warmup_epoch=0):
|
||||
super(CosineL2Decay, self).__init__()
|
||||
self.start_factor = float(factor)
|
||||
self.end_factor = float(end_factor)
|
||||
self.warmup_epoch = warmup_epoch
|
||||
|
||||
def __call__(self):
|
||||
return self.start_factor
|
||||
@@ -0,0 +1,123 @@
|
||||
# copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import math
|
||||
|
||||
import paddle
|
||||
|
||||
|
||||
class ModelEMA:
|
||||
"""Exponential Moving Average for model parameters.
|
||||
|
||||
Maintains shadow copies of model parameters and updates them with:
|
||||
ema_param = decay * ema_param + (1 - decay) * cur_param
|
||||
|
||||
Reference: PaddleDetection ppdet/optimizer/ema.py
|
||||
|
||||
Args:
|
||||
model (nn.Layer): The model whose parameters will be averaged.
|
||||
decay (float): EMA decay coefficient. Default: 0.9998.
|
||||
gamma (int): Warmup parameter for threshold/exponential decay.
|
||||
Default: 2000.
|
||||
ema_decay_type (str): Decay schedule type, one of
|
||||
'threshold' (default), 'exponential', 'normal'.
|
||||
ema_filter_no_grad (bool): If True, parameters with
|
||||
stop_gradient=True (e.g. frozen Teacher in distillation)
|
||||
are excluded from EMA and pass through unchanged.
|
||||
BN running stats are kept even if no-grad. Default: False.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model,
|
||||
decay=0.9998,
|
||||
gamma=2000,
|
||||
ema_decay_type="threshold",
|
||||
ema_filter_no_grad=False,
|
||||
):
|
||||
self.decay = decay
|
||||
self.gamma = gamma
|
||||
self.ema_decay_type = ema_decay_type
|
||||
self.step = 0
|
||||
self._decay = decay
|
||||
|
||||
# Build black list: frozen params (excluding BN running stats)
|
||||
self.ema_black_list = set()
|
||||
if ema_filter_no_grad:
|
||||
bn_state_names = set()
|
||||
for name, layer in model.named_sublayers():
|
||||
if isinstance(layer, (paddle.nn.BatchNorm2D, paddle.nn.BatchNorm1D)):
|
||||
prefix = name + "." if name else ""
|
||||
bn_state_names.add(prefix + "_mean")
|
||||
bn_state_names.add(prefix + "_variance")
|
||||
for n, p in model.named_parameters():
|
||||
if p.stop_gradient and n not in bn_state_names:
|
||||
self.ema_black_list.add(n)
|
||||
|
||||
# Initialize shadow weights
|
||||
self.state_dict = {}
|
||||
for k, v in model.state_dict().items():
|
||||
if k in self.ema_black_list:
|
||||
self.state_dict[k] = v.clone()
|
||||
else:
|
||||
self.state_dict[k] = paddle.zeros_like(v).astype("float32")
|
||||
|
||||
def _get_decay(self):
|
||||
if self.ema_decay_type == "threshold":
|
||||
return min(self.decay, (1 + self.step) / (10 + self.step))
|
||||
elif self.ema_decay_type == "exponential":
|
||||
return self.decay * (1 - math.exp(-(self.step + 1) / self.gamma))
|
||||
else: # normal
|
||||
return self.decay
|
||||
|
||||
def update(self, model):
|
||||
"""Update shadow weights with current model parameters."""
|
||||
decay = self._get_decay()
|
||||
self._decay = decay
|
||||
model_dict = model.state_dict()
|
||||
for k, v in self.state_dict.items():
|
||||
if k not in self.ema_black_list and k in model_dict:
|
||||
v = decay * v + (1 - decay) * model_dict[k].astype("float32")
|
||||
v.stop_gradient = True
|
||||
self.state_dict[k] = v
|
||||
self.step += 1
|
||||
|
||||
def apply(self):
|
||||
"""Return bias-corrected EMA state dict for eval/save.
|
||||
|
||||
Does NOT modify internal state.
|
||||
"""
|
||||
if self.step == 0:
|
||||
return {k: v.clone() for k, v in self.state_dict.items()}
|
||||
state = {}
|
||||
for k, v in self.state_dict.items():
|
||||
if k in self.ema_black_list:
|
||||
state[k] = v
|
||||
else:
|
||||
if self.ema_decay_type != "exponential":
|
||||
# threshold / normal need bias-correction
|
||||
v = v / (1 - self._decay**self.step)
|
||||
v = v.clone()
|
||||
v.stop_gradient = True
|
||||
state[k] = v
|
||||
return state
|
||||
|
||||
def state_dict_for_save(self):
|
||||
"""Return serializable dict for checkpoint."""
|
||||
return {"ema_state": self.state_dict, "step": self.step}
|
||||
|
||||
def set_state_dict(self, d):
|
||||
"""Restore from checkpoint."""
|
||||
self.state_dict = d["ema_state"]
|
||||
self.step = d["step"]
|
||||
@@ -354,13 +354,9 @@ def dynamic_to_static(model, arch_config, logger, input_shape=None):
|
||||
],
|
||||
)
|
||||
|
||||
if (
|
||||
arch_config["model_type"] != "sr"
|
||||
and arch_config["Backbone"]["name"] == "PPLCNetV3"
|
||||
):
|
||||
# for rep lcnetv3
|
||||
if arch_config["model_type"] != "sr":
|
||||
for layer in model.sublayers():
|
||||
if hasattr(layer, "rep") and not getattr(layer, "is_repped"):
|
||||
if hasattr(layer, "rep") and not getattr(layer, "is_repped", False):
|
||||
layer.rep()
|
||||
return model
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ def _mkdir_if_not_exist(path, logger):
|
||||
raise OSError("Failed to mkdir {}".format(path))
|
||||
|
||||
|
||||
def load_model(config, model, optimizer=None, model_type="det"):
|
||||
def load_model(config, model, optimizer=None, model_type="det", ema=None):
|
||||
"""
|
||||
load model from checkpoint or pretrained_model
|
||||
"""
|
||||
@@ -161,6 +161,33 @@ def load_model(config, model, optimizer=None, model_type="det"):
|
||||
if "epoch" in states_dict:
|
||||
best_model_dict["start_epoch"] = states_dict["epoch"] + 1
|
||||
logger.info("resume from {}".format(checkpoints))
|
||||
|
||||
# Restore EMA state if available
|
||||
if ema is not None:
|
||||
pdema_path = checkpoints + ".pdema"
|
||||
if os.path.exists(pdema_path):
|
||||
ema_data = paddle.load(pdema_path)
|
||||
# .pdparams contains EMA weights; restore original training weights
|
||||
if "train_state" in ema_data:
|
||||
train_sd = ema_data["train_state"]
|
||||
cur_sd = model.state_dict()
|
||||
for k in cur_sd:
|
||||
if k in train_sd:
|
||||
if list(cur_sd[k].shape) == list(train_sd[k].shape):
|
||||
cur_sd[k] = train_sd[k]
|
||||
model.set_state_dict(cur_sd)
|
||||
logger.info(
|
||||
"EMA: restored training weights from {}".format(pdema_path)
|
||||
)
|
||||
# Restore EMA shadow weights + step
|
||||
if "ema_state" in ema_data and "step" in ema_data:
|
||||
ema.set_state_dict(ema_data)
|
||||
logger.info(
|
||||
"EMA: restored shadow weights (step={}) from {}".format(
|
||||
ema_data["step"], pdema_path
|
||||
)
|
||||
)
|
||||
|
||||
elif pretrained_model:
|
||||
is_float16 = load_pretrained_params(model, pretrained_model)
|
||||
else:
|
||||
@@ -219,6 +246,8 @@ def save_model(
|
||||
config,
|
||||
is_best=False,
|
||||
prefix="ppocr",
|
||||
ema=None,
|
||||
train_state=None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -244,10 +273,30 @@ def save_model(
|
||||
paddle.save(model.state_dict(), model_prefix + ".pdparams")
|
||||
metric_prefix = model_prefix
|
||||
|
||||
# Save EMA state for training resumption
|
||||
if ema is not None and train_state is not None:
|
||||
paddle.save(
|
||||
{
|
||||
"train_state": train_state,
|
||||
"ema_state": ema.state_dict,
|
||||
"step": ema.step,
|
||||
},
|
||||
model_prefix + ".pdema",
|
||||
)
|
||||
|
||||
if prefix == "best_accuracy":
|
||||
paddle.save(
|
||||
model.state_dict(), os.path.join(best_model_path, "model.pdparams")
|
||||
)
|
||||
if ema is not None and train_state is not None:
|
||||
paddle.save(
|
||||
{
|
||||
"train_state": train_state,
|
||||
"ema_state": ema.state_dict,
|
||||
"step": ema.step,
|
||||
},
|
||||
os.path.join(best_model_path, "model.pdema"),
|
||||
)
|
||||
|
||||
else: # for kie system, we follow the save/load rules in NLP
|
||||
if config["Global"]["distributed"]:
|
||||
|
||||
@@ -134,6 +134,18 @@ def test_iaa_augment_custom(sample_image, sample_polys):
|
||||
assert polys_changed, "Polygons should have been transformed"
|
||||
|
||||
|
||||
def test_iaa_augment_affine_fit_output(sample_image, sample_polys):
|
||||
data = create_data(sample_image, sample_polys)
|
||||
augmenter_args = [
|
||||
{"type": "Affine", "args": {"rotate": [45, 45], "fit_output": True}},
|
||||
]
|
||||
augmenter = IaaAugment(augmenter_args=augmenter_args)
|
||||
transformed_data = augmenter(data)
|
||||
|
||||
assert transformed_data["image"].shape[0] > sample_image.shape[0]
|
||||
assert transformed_data["image"].shape[1] > sample_image.shape[1]
|
||||
|
||||
|
||||
# Test that an unknown transformation type raises an AttributeError
|
||||
def test_iaa_augment_unknown_transform():
|
||||
augmenter_args = [{"type": "UnknownTransform", "args": {}}]
|
||||
|
||||
+8
-1
@@ -81,8 +81,15 @@ def main():
|
||||
os.makedirs(os.path.dirname(save_res_path))
|
||||
|
||||
model.eval()
|
||||
infer_img = config["Global"]["infer_img"]
|
||||
# Support txt file containing one image path per line
|
||||
if infer_img.endswith(".txt") and os.path.isfile(infer_img):
|
||||
with open(infer_img, "r") as f:
|
||||
img_file_list = [line.strip() for line in f if line.strip()]
|
||||
else:
|
||||
img_file_list = get_image_file_list(infer_img)
|
||||
with open(save_res_path, "wb") as fout:
|
||||
for file in get_image_file_list(config["Global"]["infer_img"]):
|
||||
for file in img_file_list:
|
||||
logger.info("infer_img: {}".format(file))
|
||||
with open(file, "rb") as f:
|
||||
img = f.read()
|
||||
|
||||
+51
-3
@@ -217,6 +217,8 @@ def train(
|
||||
amp_custom_black_list=[],
|
||||
amp_custom_white_list=[],
|
||||
amp_dtype="float16",
|
||||
wd_scheduler=None,
|
||||
ema=None,
|
||||
):
|
||||
cal_metric_during_train = config["Global"].get("cal_metric_during_train", False)
|
||||
calc_epoch_interval = config["Global"].get("calc_epoch_interval", 1)
|
||||
@@ -316,14 +318,17 @@ def train(
|
||||
|
||||
for epoch in range(start_epoch, epoch_num + 1):
|
||||
if train_dataloader.dataset.need_reset:
|
||||
train_dataloader = build_dataloader(
|
||||
config, "Train", device, logger, seed=epoch
|
||||
)
|
||||
# Update index mapping + shared epoch (no disk I/O, no worker restart)
|
||||
train_dataloader.dataset.reset_data_lines(seed=epoch, epoch=epoch)
|
||||
max_iter = (
|
||||
len(train_dataloader) - 1
|
||||
if platform.system() == "Windows"
|
||||
else len(train_dataloader)
|
||||
)
|
||||
# Match original behavior: fresh DistributedBatchSampler always
|
||||
# starts with self.epoch=0 for its internal np shuffle seed
|
||||
if hasattr(train_dataloader.batch_sampler, "set_epoch"):
|
||||
train_dataloader.batch_sampler.set_epoch(0)
|
||||
|
||||
for idx, batch in enumerate(train_dataloader):
|
||||
model.train()
|
||||
@@ -393,6 +398,9 @@ def train(
|
||||
|
||||
optimizer.clear_grad()
|
||||
|
||||
if ema is not None:
|
||||
ema.update(model)
|
||||
|
||||
if (
|
||||
cal_metric_during_train and epoch % calc_epoch_interval == 0
|
||||
): # only rec and cls need
|
||||
@@ -448,12 +456,17 @@ def train(
|
||||
if not isinstance(lr_scheduler, float):
|
||||
lr_scheduler.step()
|
||||
|
||||
if wd_scheduler is not None:
|
||||
wd_scheduler.step()
|
||||
|
||||
# logger and visualdl
|
||||
stats = {
|
||||
k: float(v) if v.shape == [] else v.numpy().mean()
|
||||
for k, v in loss.items()
|
||||
}
|
||||
stats["lr"] = lr
|
||||
if wd_scheduler is not None:
|
||||
stats["wd"] = wd_scheduler.get_wd()
|
||||
train_stats.update(stats)
|
||||
|
||||
if log_writer is not None and dist.get_rank() == 0:
|
||||
@@ -511,6 +524,11 @@ def train(
|
||||
max_average_window=15625,
|
||||
)
|
||||
Model_Average.apply()
|
||||
# Apply EMA weights for eval and save
|
||||
_ema_train_state = None
|
||||
if ema is not None:
|
||||
_ema_train_state = copy.deepcopy(model.state_dict())
|
||||
model.set_state_dict(ema.apply())
|
||||
cur_metric = eval(
|
||||
model,
|
||||
valid_dataloader,
|
||||
@@ -561,6 +579,8 @@ def train(
|
||||
config,
|
||||
is_best=True,
|
||||
prefix=prefix,
|
||||
ema=ema,
|
||||
train_state=_ema_train_state,
|
||||
save_model_info=model_info,
|
||||
best_model_dict=best_model_dict,
|
||||
epoch=epoch,
|
||||
@@ -588,9 +608,18 @@ def train(
|
||||
is_best=True, prefix="best_accuracy", metadata=best_model_dict
|
||||
)
|
||||
|
||||
# Restore training weights after eval/save
|
||||
if _ema_train_state is not None:
|
||||
model.set_state_dict(_ema_train_state)
|
||||
|
||||
reader_start = time.time()
|
||||
if dist.get_rank() == 0:
|
||||
prefix = "latest"
|
||||
# Apply EMA weights for save
|
||||
_ema_train_state_latest = None
|
||||
if ema is not None:
|
||||
_ema_train_state_latest = copy.deepcopy(model.state_dict())
|
||||
model.set_state_dict(ema.apply())
|
||||
if uniform_output_enabled:
|
||||
export(config, model, os.path.join(save_model_dir, prefix, "inference"))
|
||||
gc.collect()
|
||||
@@ -609,17 +638,27 @@ def train(
|
||||
config,
|
||||
is_best=False,
|
||||
prefix=prefix,
|
||||
ema=ema,
|
||||
train_state=_ema_train_state_latest,
|
||||
save_model_info=model_info,
|
||||
best_model_dict=best_model_dict,
|
||||
epoch=epoch,
|
||||
global_step=global_step,
|
||||
)
|
||||
# Restore training weights
|
||||
if _ema_train_state_latest is not None:
|
||||
model.set_state_dict(_ema_train_state_latest)
|
||||
|
||||
if log_writer is not None:
|
||||
log_writer.log_model(is_best=False, prefix="latest")
|
||||
|
||||
if dist.get_rank() == 0 and epoch > 0 and epoch % save_epoch_step == 0:
|
||||
prefix = "iter_epoch_{}".format(epoch)
|
||||
# Apply EMA weights for save
|
||||
_ema_train_state_iter = None
|
||||
if ema is not None:
|
||||
_ema_train_state_iter = copy.deepcopy(model.state_dict())
|
||||
model.set_state_dict(ema.apply())
|
||||
if uniform_output_enabled:
|
||||
export(config, model, os.path.join(save_model_dir, prefix, "inference"))
|
||||
gc.collect()
|
||||
@@ -638,17 +677,26 @@ def train(
|
||||
config,
|
||||
is_best=False,
|
||||
prefix=prefix,
|
||||
ema=ema,
|
||||
train_state=_ema_train_state_iter,
|
||||
save_model_info=model_info,
|
||||
best_model_dict=best_model_dict,
|
||||
epoch=epoch,
|
||||
global_step=global_step,
|
||||
done_flag=epoch == config["Global"]["epoch_num"],
|
||||
)
|
||||
# Restore training weights
|
||||
if _ema_train_state_iter is not None:
|
||||
model.set_state_dict(_ema_train_state_iter)
|
||||
if log_writer is not None:
|
||||
log_writer.log_model(
|
||||
is_best=False, prefix="iter_epoch_{}".format(epoch)
|
||||
)
|
||||
|
||||
# Reset reader_start so next epoch's first batch doesn't include
|
||||
# save_model time in avg_reader_cost
|
||||
reader_start = time.time()
|
||||
|
||||
best_str = "best metric, {}".format(
|
||||
", ".join(["{}: {}".format(k, v) for k, v in best_model_dict.items()])
|
||||
)
|
||||
|
||||
+34
-6
@@ -43,7 +43,7 @@ import tools.naive_sync_bn as naive_sync_bn
|
||||
dist.get_world_size()
|
||||
|
||||
|
||||
def main(config, device, logger, vdl_writer, seed):
|
||||
def main(config, device, logger, vdl_writer):
|
||||
# init dist environment
|
||||
if config["Global"]["distributed"]:
|
||||
dist.init_parallel_env()
|
||||
@@ -51,8 +51,13 @@ def main(config, device, logger, vdl_writer, seed):
|
||||
global_config = config["Global"]
|
||||
|
||||
# build dataloader
|
||||
# NOTE: Do NOT pass seed here. The seed parameter in build_dataloader is used
|
||||
# as epoch number by set_epoch_as_seed (for adaptive shrink_ratio), not as
|
||||
# random seed. First construction should use epoch=0 (i.e., seed=None).
|
||||
# The epoch loop in program.train() handles subsequent updates via
|
||||
# reset_data_lines(seed=epoch).
|
||||
set_signal_handlers()
|
||||
train_dataloader = build_dataloader(config, "Train", device, logger, seed)
|
||||
train_dataloader = build_dataloader(config, "Train", device, logger)
|
||||
if len(train_dataloader) == 0:
|
||||
logger.error(
|
||||
"No Images in train dataset, please ensure\n"
|
||||
@@ -62,7 +67,7 @@ def main(config, device, logger, vdl_writer, seed):
|
||||
return
|
||||
|
||||
if config["Eval"]:
|
||||
valid_dataloader = build_dataloader(config, "Eval", device, logger, seed)
|
||||
valid_dataloader = build_dataloader(config, "Eval", device, logger)
|
||||
else:
|
||||
valid_dataloader = None
|
||||
step_pre_epoch = len(train_dataloader)
|
||||
@@ -154,7 +159,7 @@ def main(config, device, logger, vdl_writer, seed):
|
||||
loss_class = build_loss(config["Loss"])
|
||||
|
||||
# build optim
|
||||
optimizer, lr_scheduler = build_optimizer(
|
||||
optimizer, lr_scheduler, wd_scheduler = build_optimizer(
|
||||
config["Optimizer"],
|
||||
epochs=config["Global"]["epoch_num"],
|
||||
step_each_epoch=len(train_dataloader),
|
||||
@@ -211,9 +216,30 @@ def main(config, device, logger, vdl_writer, seed):
|
||||
else:
|
||||
scaler = None
|
||||
|
||||
# build EMA (after AMP decorate, before load_model)
|
||||
ema = None
|
||||
if config["Global"].get("use_ema", False):
|
||||
from ppocr.utils.ema import ModelEMA
|
||||
|
||||
ema = ModelEMA(
|
||||
model,
|
||||
decay=config["Global"].get("ema_decay", 0.9998),
|
||||
gamma=config["Global"].get("ema_gamma", 2000),
|
||||
ema_decay_type=config["Global"].get("ema_decay_type", "threshold"),
|
||||
ema_filter_no_grad=config["Global"].get("ema_filter_no_grad", False),
|
||||
)
|
||||
logger.info(
|
||||
"EMA enabled: decay={}, gamma={}, type={}, filter_no_grad={}".format(
|
||||
ema.decay,
|
||||
ema.gamma,
|
||||
ema.ema_decay_type,
|
||||
config["Global"].get("ema_filter_no_grad", False),
|
||||
)
|
||||
)
|
||||
|
||||
# load pretrain model
|
||||
pre_best_model_dict = load_model(
|
||||
config, model, optimizer, config["Architecture"]["model_type"]
|
||||
config, model, optimizer, config["Architecture"]["model_type"], ema=ema
|
||||
)
|
||||
|
||||
if config["Global"]["distributed"]:
|
||||
@@ -242,6 +268,8 @@ def main(config, device, logger, vdl_writer, seed):
|
||||
amp_custom_black_list,
|
||||
amp_custom_white_list,
|
||||
amp_dtype,
|
||||
wd_scheduler=wd_scheduler,
|
||||
ema=ema,
|
||||
)
|
||||
|
||||
|
||||
@@ -269,5 +297,5 @@ if __name__ == "__main__":
|
||||
config, device, logger, vdl_writer = program.preprocess(is_train=True)
|
||||
seed = config["Global"]["seed"] if "seed" in config["Global"] else 1024
|
||||
set_seed(seed)
|
||||
main(config, device, logger, vdl_writer, seed)
|
||||
main(config, device, logger, vdl_writer)
|
||||
# test_reader(config, device, logger)
|
||||
Reference in new issue
Block a user