Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/logs/lta_owt_bert_absrope_time4_dirichlet_len128_C1_to_1024_mask1_sameT_gbs512_b32_4gpu_1m_save1k_20260525_watcher.sh +87 -0
- LTA_openwebtext_dualt/logs/lta_owt_c1024_gpt2_cached_len128_exact100_repeat1024_4gpu_200step.log +82 -0
- LTA_openwebtext_dualt/logs/owt_fully_best_readability_candidates_step118k_n64.log +37 -0
- LTA_openwebtext_dualt/logs/smoke_duo_aligned_1gpu_b64_metricsbf16.log +79 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_logical/foo77.f +56 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_real/foo77.f +45 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ctrl/configuration_ctrl.py +70 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ctrl/modeling_ctrl.py +683 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/doge/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pp_ocrv5_server_det/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pp_ocrv5_server_det/configuration_pp_ocrv5_server_det.py +87 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pp_ocrv5_server_det/modular_pp_ocrv5_server_det.py +909 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_088000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_202000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_224000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_230000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_354000.pt +3 -0
LTA_openwebtext_dualt/logs/lta_owt_bert_absrope_time4_dirichlet_len128_C1_to_1024_mask1_sameT_gbs512_b32_4gpu_1m_save1k_20260525_watcher.sh
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
cd /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt
|
| 5 |
+
export PYTHONPATH="$(pwd)${PYTHONPATH:+:$PYTHONPATH}"
|
| 6 |
+
export TOKENIZERS_PARALLELISM=false
|
| 7 |
+
export PYTHONUNBUFFERED=1
|
| 8 |
+
|
| 9 |
+
: "${RUN_DIR:?RUN_DIR is required}"
|
| 10 |
+
: "${OUT_BASE:?OUT_BASE is required}"
|
| 11 |
+
: "${LOG_DIR:?LOG_DIR is required}"
|
| 12 |
+
: "${TOKENIZER_PATH:?TOKENIZER_PATH is required}"
|
| 13 |
+
: "${SCORER:?SCORER is required}"
|
| 14 |
+
|
| 15 |
+
RUN_STEM="$(basename "${RUN_DIR}")"
|
| 16 |
+
TEMP_TAG="${ENDPOINT_TEMP//./p}"
|
| 17 |
+
PROCESSED_FILE="${LOG_DIR}/processed_${RUN_STEM}_steps${STEPS}_c${CMIN}_${CMAX}_gumbel_t${TEMP_TAG}_n${N_SAMPLES}.txt"
|
| 18 |
+
|
| 19 |
+
mkdir -p "${OUT_BASE}" "${LOG_DIR}"
|
| 20 |
+
touch "${PROCESSED_FILE}"
|
| 21 |
+
|
| 22 |
+
echo "[watch-gumbel] run_dir=${RUN_DIR}"
|
| 23 |
+
echo "[watch-gumbel] out_base=${OUT_BASE}"
|
| 24 |
+
echo "[watch-gumbel] interval=${STEP_INTERVAL} max_len=${MAX_LEN} steps=${STEPS} c=${CMIN}->${CMAX} temp=${ENDPOINT_TEMP} top_p=${ENDPOINT_TOP_P} tau=${GUMBEL_TAU_START}->${GUMBEL_TAU_END} n=${N_SAMPLES}"
|
| 25 |
+
|
| 26 |
+
while true; do
|
| 27 |
+
shopt -s nullglob
|
| 28 |
+
ckpts=("${RUN_DIR}"/step_*.pt)
|
| 29 |
+
shopt -u nullglob
|
| 30 |
+
|
| 31 |
+
if (( ${#ckpts[@]} == 0 )); then
|
| 32 |
+
echo "[watch-gumbel] $(date +%F_%T) no ckpt yet"
|
| 33 |
+
sleep "${SLEEP_SECONDS}"
|
| 34 |
+
continue
|
| 35 |
+
fi
|
| 36 |
+
|
| 37 |
+
printf "%s\n" "${ckpts[@]}" | sort | while read -r ckpt; do
|
| 38 |
+
base="$(basename "${ckpt}")"
|
| 39 |
+
step="${base#step_}"
|
| 40 |
+
step="${step%.pt}"
|
| 41 |
+
step_num=$((10#${step}))
|
| 42 |
+
if (( step_num % STEP_INTERVAL != 0 )); then
|
| 43 |
+
continue
|
| 44 |
+
fi
|
| 45 |
+
if grep -Fxq "${ckpt}" "${PROCESSED_FILE}"; then
|
| 46 |
+
continue
|
| 47 |
+
fi
|
| 48 |
+
|
| 49 |
+
out_dir="${OUT_BASE}/step_${step}"
|
| 50 |
+
log_file="${LOG_DIR}/infer_${RUN_STEM}_step_${step}.log"
|
| 51 |
+
mkdir -p "${out_dir}"
|
| 52 |
+
|
| 53 |
+
echo "[watch-gumbel] $(date +%F_%T) infer ${ckpt} -> ${out_dir}" | tee -a "${log_file}"
|
| 54 |
+
CUDA_VISIBLE_DEVICES="${WATCH_CUDA_VISIBLE_DEVICES}" python scripts/eval_lm1b_c1024_fullycoupled_sde_genppl.py \
|
| 55 |
+
--checkpoint "${ckpt}" \
|
| 56 |
+
--tokenizer_path "${TOKENIZER_PATH}" \
|
| 57 |
+
--scorer "${SCORER}" \
|
| 58 |
+
--out_dir "${out_dir}" \
|
| 59 |
+
--n_samples "${N_SAMPLES}" \
|
| 60 |
+
--max_len "${MAX_LEN}" \
|
| 61 |
+
--steps "${STEPS}" \
|
| 62 |
+
--batch_size "${DECODE_BATCH}" \
|
| 63 |
+
--score_batch "${SCORE_BATCH}" \
|
| 64 |
+
--score_max_length "${SCORE_MAX_LENGTH}" \
|
| 65 |
+
--concentration_min "${CMIN}" \
|
| 66 |
+
--concentration_max "${CMAX}" \
|
| 67 |
+
--endpoint_temp "${ENDPOINT_TEMP}" \
|
| 68 |
+
--endpoint_projection gumbel_softmax \
|
| 69 |
+
--endpoint_top_p "${ENDPOINT_TOP_P}" \
|
| 70 |
+
--gumbel_tau_start "${GUMBEL_TAU_START}" \
|
| 71 |
+
--gumbel_tau_end "${GUMBEL_TAU_END}" \
|
| 72 |
+
--model_t_mode support_t \
|
| 73 |
+
--mean_mode endpoint_only \
|
| 74 |
+
--semantic_power 1.0 \
|
| 75 |
+
--noise_init dirichlet \
|
| 76 |
+
--noise_dirichlet_concentration "${CMIN}" \
|
| 77 |
+
--sde_resample dirichlet \
|
| 78 |
+
--final_from blend_0.5 \
|
| 79 |
+
--seed 20260524 \
|
| 80 |
+
2>&1 | tee -a "${log_file}"
|
| 81 |
+
|
| 82 |
+
echo "${ckpt}" >> "${PROCESSED_FILE}"
|
| 83 |
+
echo "[watch-gumbel] $(date +%F_%T) done step_${step}" | tee -a "${log_file}"
|
| 84 |
+
done
|
| 85 |
+
|
| 86 |
+
sleep "${SLEEP_SECONDS}"
|
| 87 |
+
done
|
LTA_openwebtext_dualt/logs/lta_owt_c1024_gpt2_cached_len128_exact100_repeat1024_4gpu_200step.log
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
*****************************************
|
| 3 |
+
Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed.
|
| 4 |
+
*****************************************
|
| 5 |
+
[rank0]:[W512 19:39:24.800276910 ProcessGroupNCCL.cpp:4571] [PG ID 0 PG GUID 0 Rank 0] using GPU 0 to perform barrier as devices used by this process are currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. Specify device_ids in barrier() to force use of a particular device, or call init_process_group() with a device_id.
|
| 6 |
+
[rank1]:[W512 19:39:26.534674590 ProcessGroupNCCL.cpp:4571] [PG ID 0 PG GUID 0 Rank 1] using GPU 1 to perform barrier as devices used by this process are currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. Specify device_ids in barrier() to force use of a particular device, or call init_process_group() with a device_id.
|
| 7 |
+
[rank3]:[W512 19:39:27.828159040 ProcessGroupNCCL.cpp:4571] [PG ID 0 PG GUID 0 Rank 3] using GPU 3 to perform barrier as devices used by this process are currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. Specify device_ids in barrier() to force use of a particular device, or call init_process_group() with a device_id.
|
| 8 |
+
[rank2]:[W512 19:39:27.927014715 ProcessGroupNCCL.cpp:4571] [PG ID 0 PG GUID 0 Rank 2] using GPU 2 to perform barrier as devices used by this process are currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. Specify device_ids in barrier() to force use of a particular device, or call init_process_group() with a device_id.
|
| 9 |
+
{
|
| 10 |
+
"device": "cuda:0",
|
| 11 |
+
"rank": 0,
|
| 12 |
+
"world_size": 4,
|
| 13 |
+
"samples": "owt_cached_chunks:100",
|
| 14 |
+
"vocab_size": 50257,
|
| 15 |
+
"save_dir": "runs/lta_owt_c1024_gpt2_cached_len128_exact100_repeat1024_4gpu_200step",
|
| 16 |
+
"batch_size": 32,
|
| 17 |
+
"grad_accum": 4,
|
| 18 |
+
"effective_batch_size": 512,
|
| 19 |
+
"global_batch_size": 512,
|
| 20 |
+
"lr_schedule": "constant_warmup",
|
| 21 |
+
"warmup_steps": 20,
|
| 22 |
+
"adam_beta1": 0.9,
|
| 23 |
+
"adam_beta2": 0.999,
|
| 24 |
+
"adam_eps": 1e-08,
|
| 25 |
+
"model_type": "ddit",
|
| 26 |
+
"dual_t": true,
|
| 27 |
+
"corrupt_t_mode": "same",
|
| 28 |
+
"corrupt_min_t": 0.0,
|
| 29 |
+
"corrupt_max_t": 1.0,
|
| 30 |
+
"dirichlet_endpoint_mode": "categorical_dual_t",
|
| 31 |
+
"dirichlet_semantic_t_mode": "same",
|
| 32 |
+
"dirichlet_semantic_t_value": 0.0,
|
| 33 |
+
"categorical_wrong_from_full_vocab": true,
|
| 34 |
+
"simplex_bridge_sampler": "dirichlet",
|
| 35 |
+
"logistic_normal_sigma_min": 0.18,
|
| 36 |
+
"logistic_normal_sigma_max": 2.2,
|
| 37 |
+
"logistic_normal_tau_min": 0.65,
|
| 38 |
+
"logistic_normal_tau_max": 1.15,
|
| 39 |
+
"torch_compile": false,
|
| 40 |
+
"compile_mode": "max-autotune",
|
| 41 |
+
"state_format": "prob",
|
| 42 |
+
"target_loss": "hard_ce",
|
| 43 |
+
"meanflow_weight": 0.0,
|
| 44 |
+
"bridge_noise_init": "logistic_normal",
|
| 45 |
+
"noise_sigma": -1.0,
|
| 46 |
+
"wrap": true,
|
| 47 |
+
"wrap_mode": "stream",
|
| 48 |
+
"wrap_record_buffer_size": 200,
|
| 49 |
+
"owt_cached_chunks": true,
|
| 50 |
+
"owt_chunk_cache_dir": "/e2e-data/evad-tech-vla/wanghan58/data/small_benchmarks/langflow_2604_11748/openwebtext_lta_cached_chunks/gpt2_len128_train_minus_100k_exact100",
|
| 51 |
+
"owt_chunk_cache_rebuild": false,
|
| 52 |
+
"owt_chunk_cache_write_batch": 4096,
|
| 53 |
+
"owt_exact_repeat_per_chunk": 1024,
|
| 54 |
+
"online_chunk_shuffle": false,
|
| 55 |
+
"online_chunk_shuffle_buffer": 10000,
|
| 56 |
+
"openwebtext_split": "train_minus_100k",
|
| 57 |
+
"detokenizer": "auto",
|
| 58 |
+
"resolved_detokenizer": null,
|
| 59 |
+
"num_workers": 0,
|
| 60 |
+
"latest_every": 50,
|
| 61 |
+
"resume_path": ""
|
| 62 |
+
}
|
| 63 |
+
step=10 micro_steps=40 elapsed=5.2s lr=1.650000e-04 loss_all=10.6384 acc_all=0.5972 loss_corrupt=10.6582 acc_corrupt=0.3944 corrupt_frac=0.5412 loss=10.6582 loss_recon=10.6582 loss_meanflow=0.0000 mean_model_t=0.5116 mean_corrupt_t=0.5116 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4917 init_acc_corrupt=0.4742 init_gold_top10=0.5029 init_gold_top100=0.5308
|
| 64 |
+
step=20 micro_steps=80 elapsed=4.4s lr=3.000000e-04 loss_all=9.1266 acc_all=0.0782 loss_corrupt=9.1391 acc_corrupt=0.0574 corrupt_frac=0.5459 loss=9.1391 loss_recon=9.1391 loss_meanflow=0.0000 mean_model_t=0.5069 mean_corrupt_t=0.5069 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4957 init_acc_corrupt=0.4725 init_gold_top10=0.4992 init_gold_top100=0.5266
|
| 65 |
+
step=30 micro_steps=120 elapsed=4.4s lr=3.000000e-04 loss_all=7.1634 acc_all=0.0552 loss_corrupt=7.1695 acc_corrupt=0.0463 corrupt_frac=0.5441 loss=7.1695 loss_recon=7.1695 loss_meanflow=0.0000 mean_model_t=0.5013 mean_corrupt_t=0.5013 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4968 init_acc_corrupt=0.4697 init_gold_top10=0.4977 init_gold_top100=0.5260
|
| 66 |
+
step=40 micro_steps=160 elapsed=4.4s lr=3.000000e-04 loss_all=6.5580 acc_all=0.1148 loss_corrupt=6.5872 acc_corrupt=0.0892 corrupt_frac=0.5593 loss=6.5872 loss_recon=6.5872 loss_meanflow=0.0000 mean_model_t=0.4933 mean_corrupt_t=0.4933 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5044 init_acc_corrupt=0.4601 init_gold_top10=0.4892 init_gold_top100=0.5202
|
| 67 |
+
step=50 micro_steps=200 elapsed=4.4s lr=3.000000e-04 loss_all=6.1045 acc_all=0.1572 loss_corrupt=6.3032 acc_corrupt=0.1170 corrupt_frac=0.5444 loss=6.3032 loss_recon=6.3032 loss_meanflow=0.0000 mean_model_t=0.4978 mean_corrupt_t=0.4978 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5076 init_acc_corrupt=0.4556 init_gold_top10=0.4863 init_gold_top100=0.5171
|
| 68 |
+
step=60 micro_steps=240 elapsed=6.3s lr=3.000000e-04 loss_all=5.2158 acc_all=0.2475 loss_corrupt=5.7240 acc_corrupt=0.1806 corrupt_frac=0.5518 loss=5.7240 loss_recon=5.7240 loss_meanflow=0.0000 mean_model_t=0.4948 mean_corrupt_t=0.4948 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4978 init_acc_corrupt=0.4666 init_gold_top10=0.4959 init_gold_top100=0.5253
|
| 69 |
+
step=70 micro_steps=280 elapsed=4.4s lr=3.000000e-04 loss_all=3.7862 acc_all=0.4467 loss_corrupt=4.7490 acc_corrupt=0.3154 corrupt_frac=0.5588 loss=4.7490 loss_recon=4.7490 loss_meanflow=0.0000 mean_model_t=0.5086 mean_corrupt_t=0.5086 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4901 init_acc_corrupt=0.4773 init_gold_top10=0.5046 init_gold_top100=0.5324
|
| 70 |
+
step=80 micro_steps=320 elapsed=4.4s lr=3.000000e-04 loss_all=2.3615 acc_all=0.6930 loss_corrupt=3.7446 acc_corrupt=0.4822 corrupt_frac=0.5547 loss=3.7446 loss_recon=3.7446 loss_meanflow=0.0000 mean_model_t=0.5120 mean_corrupt_t=0.5120 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4870 init_acc_corrupt=0.4780 init_gold_top10=0.5076 init_gold_top100=0.5345
|
| 71 |
+
step=90 micro_steps=360 elapsed=4.3s lr=3.000000e-04 loss_all=1.9835 acc_all=0.7175 loss_corrupt=3.5661 acc_corrupt=0.4852 corrupt_frac=0.5486 loss=3.5661 loss_recon=3.5661 loss_meanflow=0.0000 mean_model_t=0.4835 mean_corrupt_t=0.4835 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5183 init_acc_corrupt=0.4448 init_gold_top10=0.4758 init_gold_top100=0.5060
|
| 72 |
+
step=100 micro_steps=400 elapsed=4.4s lr=3.000000e-04 loss_all=1.7581 acc_all=0.7366 loss_corrupt=3.2161 acc_corrupt=0.5149 corrupt_frac=0.5428 loss=3.2161 loss_recon=3.2161 loss_meanflow=0.0000 mean_model_t=0.4994 mean_corrupt_t=0.4994 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4977 init_acc_corrupt=0.4669 init_gold_top10=0.4967 init_gold_top100=0.5264
|
| 73 |
+
step=110 micro_steps=440 elapsed=8.2s lr=3.000000e-04 loss_all=1.7078 acc_all=0.7263 loss_corrupt=2.9909 acc_corrupt=0.5182 corrupt_frac=0.5686 loss=2.9909 loss_recon=2.9909 loss_meanflow=0.0000 mean_model_t=0.4964 mean_corrupt_t=0.4964 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5031 init_acc_corrupt=0.4605 init_gold_top10=0.4914 init_gold_top100=0.5207
|
| 74 |
+
step=120 micro_steps=480 elapsed=4.4s lr=3.000000e-04 loss_all=1.4249 acc_all=0.7508 loss_corrupt=2.5742 acc_corrupt=0.5479 corrupt_frac=0.5513 loss=2.5742 loss_recon=2.5742 loss_meanflow=0.0000 mean_model_t=0.5146 mean_corrupt_t=0.5146 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4851 init_acc_corrupt=0.4828 init_gold_top10=0.5095 init_gold_top100=0.5358
|
| 75 |
+
step=130 micro_steps=520 elapsed=4.4s lr=3.000000e-04 loss_all=1.2788 acc_all=0.7603 loss_corrupt=2.2817 acc_corrupt=0.5710 corrupt_frac=0.5575 loss=2.2817 loss_recon=2.2817 loss_meanflow=0.0000 mean_model_t=0.5137 mean_corrupt_t=0.5137 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4879 init_acc_corrupt=0.4815 init_gold_top10=0.5071 init_gold_top100=0.5336
|
| 76 |
+
step=140 micro_steps=560 elapsed=4.4s lr=3.000000e-04 loss_all=1.0687 acc_all=0.7866 loss_corrupt=1.9329 acc_corrupt=0.6128 corrupt_frac=0.5491 loss=1.9329 loss_recon=1.9329 loss_meanflow=0.0000 mean_model_t=0.5159 mean_corrupt_t=0.5159 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4843 init_acc_corrupt=0.4836 init_gold_top10=0.5111 init_gold_top100=0.5365
|
| 77 |
+
step=150 micro_steps=600 elapsed=4.4s lr=3.000000e-04 loss_all=0.8887 acc_all=0.8133 loss_corrupt=1.6236 acc_corrupt=0.6579 corrupt_frac=0.5443 loss=1.6236 loss_recon=1.6236 loss_meanflow=0.0000 mean_model_t=0.5080 mean_corrupt_t=0.5080 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4939 init_acc_corrupt=0.4731 init_gold_top10=0.5004 init_gold_top100=0.5300
|
| 78 |
+
step=160 micro_steps=640 elapsed=6.3s lr=3.000000e-04 loss_all=0.7285 acc_all=0.8367 loss_corrupt=1.3140 acc_corrupt=0.7047 corrupt_frac=0.5513 loss=1.3140 loss_recon=1.3140 loss_meanflow=0.0000 mean_model_t=0.4908 mean_corrupt_t=0.4908 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5037 init_acc_corrupt=0.4598 init_gold_top10=0.4898 init_gold_top100=0.5208
|
| 79 |
+
step=170 micro_steps=680 elapsed=4.4s lr=3.000000e-04 loss_all=0.5558 acc_all=0.8735 loss_corrupt=0.9953 acc_corrupt=0.7733 corrupt_frac=0.5542 loss=0.9953 loss_recon=0.9953 loss_meanflow=0.0000 mean_model_t=0.5036 mean_corrupt_t=0.5036 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4968 init_acc_corrupt=0.4688 init_gold_top10=0.4973 init_gold_top100=0.5265
|
| 80 |
+
step=180 micro_steps=720 elapsed=4.4s lr=3.000000e-04 loss_all=0.4730 acc_all=0.8938 loss_corrupt=0.8661 acc_corrupt=0.8054 corrupt_frac=0.5428 loss=0.8661 loss_recon=0.8661 loss_meanflow=0.0000 mean_model_t=0.4963 mean_corrupt_t=0.4963 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5086 init_acc_corrupt=0.4558 init_gold_top10=0.4856 init_gold_top100=0.5150
|
| 81 |
+
step=190 micro_steps=760 elapsed=4.4s lr=3.000000e-04 loss_all=0.3720 acc_all=0.9130 loss_corrupt=0.6561 acc_corrupt=0.8461 corrupt_frac=0.5595 loss=0.6561 loss_recon=0.6561 loss_meanflow=0.0000 mean_model_t=0.4869 mean_corrupt_t=0.4869 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.5022 init_acc_corrupt=0.4608 init_gold_top10=0.4918 init_gold_top100=0.5221
|
| 82 |
+
step=200 micro_steps=800 elapsed=4.4s lr=3.000000e-04 loss_all=0.2823 acc_all=0.9325 loss_corrupt=0.5093 acc_corrupt=0.8780 corrupt_frac=0.5526 loss=0.5093 loss_recon=0.5093 loss_meanflow=0.0000 mean_model_t=0.5022 mean_corrupt_t=0.5022 mean_loss_t_weight=1.0000 prior_center_loss_beta=0.0000 wrong_frac=0.4950 init_acc_corrupt=0.4714 init_gold_top10=0.4992 init_gold_top100=0.5276
|
LTA_openwebtext_dualt/logs/owt_fully_best_readability_candidates_step118k_n64.log
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[forbid_endpoint_ids] n=352 first=[94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125]
|
| 2 |
+
[decode] steps24_c128_mtpost_t1p15_tpow1p0_noise0_state_anchored
|
| 3 |
+
[summary] {"name": "steps24_c128_mtpost_t1p15_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 128.0, "temp_start": 1.15, "temp_end": 1.15, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 136.68253116492195, "sample_entropy": 4.35908630001246, "distinct_1": 0.063751220703125, "distinct_2": 0.4382025904203324, "top_token_mass": 0.1629180908203125, "tokens_scored": 52925, "readability_score": 4.840462446659439, "mean_chars": 2900.390625, "replacement_chars": 0.0}
|
| 4 |
+
[decode] steps24_c128_mtpost_t1p2_tpow1p0_noise0_state_anchored
|
| 5 |
+
[summary] {"name": "steps24_c128_mtpost_t1p2_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 128.0, "temp_start": 1.2, "temp_end": 1.2, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 163.2546320727631, "sample_entropy": 4.54139086009561, "distinct_1": 0.0656280517578125, "distinct_2": 0.4883003421309873, "top_token_mass": 0.1094512939453125, "tokens_scored": 55654, "readability_score": 4.917528211030994, "mean_chars": 2910.390625, "replacement_chars": 0.0}
|
| 6 |
+
[decode] steps24_c128_mtpost_t1p25_tpow1p0_noise0_state_anchored
|
| 7 |
+
[summary] {"name": "steps24_c128_mtpost_t1p25_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 128.0, "temp_start": 1.25, "temp_end": 1.25, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 189.34256808350023, "sample_entropy": 4.6414778024588585, "distinct_1": 0.0617218017578125, "distinct_2": 0.5090573069403714, "top_token_mass": 0.0673370361328125, "tokens_scored": 57535, "readability_score": 4.951280399958232, "mean_chars": 2813.328125, "replacement_chars": 0.0}
|
| 8 |
+
[decode] steps24_c192_mtpost_t1p15_tpow1p0_noise0_state_anchored
|
| 9 |
+
[summary] {"name": "steps24_c192_mtpost_t1p15_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 192.0, "temp_start": 1.15, "temp_end": 1.15, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 110.25318817826248, "sample_entropy": 4.265044221033497, "distinct_1": 0.0598297119140625, "distinct_2": 0.4149254643206256, "top_token_mass": 0.16619873046875, "tokens_scored": 52861, "readability_score": 4.735430141224595, "mean_chars": 3033.734375, "replacement_chars": 0.0}
|
| 10 |
+
[decode] steps24_c192_mtpost_t1p2_tpow1p0_noise0_state_anchored
|
| 11 |
+
[summary] {"name": "steps24_c192_mtpost_t1p2_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 192.0, "temp_start": 1.2, "temp_end": 1.2, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 131.94485280762137, "sample_entropy": 4.424955147711324, "distinct_1": 0.06201171875, "distinct_2": 0.44993279569892475, "top_token_mass": 0.1223602294921875, "tokens_scored": 55067, "readability_score": 4.827165218600323, "mean_chars": 2980.203125, "replacement_chars": 0.0}
|
| 12 |
+
[decode] steps24_c192_mtpost_t1p25_tpow1p0_noise0_state_anchored
|
| 13 |
+
[summary] {"name": "steps24_c192_mtpost_t1p25_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 192.0, "temp_start": 1.25, "temp_end": 1.25, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 151.26706289254133, "sample_entropy": 4.510369710188292, "distinct_1": 0.058197021484375, "distinct_2": 0.4711326979472141, "top_token_mass": 0.07073974609375, "tokens_scored": 57214, "readability_score": 4.814185932885269, "mean_chars": 2938.75, "replacement_chars": 0.0}
|
| 14 |
+
[decode] steps24_c256_mtpost_t1p15_tpow1p0_noise0_state_anchored
|
| 15 |
+
[summary] {"name": "steps24_c256_mtpost_t1p15_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 256.0, "temp_start": 1.15, "temp_end": 1.15, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 102.11866506997787, "sample_entropy": 4.237296045982029, "distinct_1": 0.056640625, "distinct_2": 0.401377688172043, "top_token_mass": 0.1682281494140625, "tokens_scored": 52687, "readability_score": 4.720412153468626, "mean_chars": 3048.765625, "replacement_chars": 0.0}
|
| 16 |
+
[decode] steps24_c256_mtpost_t1p2_tpow1p0_noise0_state_anchored
|
| 17 |
+
[summary] {"name": "steps24_c256_mtpost_t1p2_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 256.0, "temp_start": 1.2, "temp_end": 1.2, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 114.33207787651192, "sample_entropy": 4.341931888548368, "distinct_1": 0.0576934814453125, "distinct_2": 0.4300617057673509, "top_token_mass": 0.1277313232421875, "tokens_scored": 54671, "readability_score": 4.762909455773018, "mean_chars": 3029.90625, "replacement_chars": 0.0}
|
| 18 |
+
[decode] steps24_c256_mtpost_t1p25_tpow1p0_noise0_state_anchored
|
| 19 |
+
[summary] {"name": "steps24_c256_mtpost_t1p25_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 24, "concentration_max": 256.0, "temp_start": 1.25, "temp_end": 1.25, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 125.85656866896282, "sample_entropy": 4.40724907644453, "distinct_1": 0.0540924072265625, "distinct_2": 0.43913428641251223, "top_token_mass": 0.0737152099609375, "tokens_scored": 57069, "readability_score": 4.71464470576572, "mean_chars": 3012.046875, "replacement_chars": 0.0}
|
| 20 |
+
[decode] steps32_c128_mtpost_t1p15_tpow1p0_noise0_state_anchored
|
| 21 |
+
[summary] {"name": "steps32_c128_mtpost_t1p15_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 128.0, "temp_start": 1.15, "temp_end": 1.15, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 93.93262211506004, "sample_entropy": 4.146366887708747, "distinct_1": 0.05560302734375, "distinct_2": 0.380330522971652, "top_token_mass": 0.1920318603515625, "tokens_scored": 51644, "readability_score": 4.702144174351347, "mean_chars": 3099.6875, "replacement_chars": 0.0}
|
| 22 |
+
[decode] steps32_c128_mtpost_t1p2_tpow1p0_noise0_state_anchored
|
| 23 |
+
[summary] {"name": "steps32_c128_mtpost_t1p2_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 128.0, "temp_start": 1.2, "temp_end": 1.2, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 109.20811571250756, "sample_entropy": 4.384182287205536, "distinct_1": 0.058258056640625, "distinct_2": 0.42856488269794724, "top_token_mass": 0.1383514404296875, "tokens_scored": 54756, "readability_score": 4.786283145660528, "mean_chars": 3182.765625, "replacement_chars": 0.0}
|
| 24 |
+
[decode] steps32_c128_mtpost_t1p25_tpow1p0_noise0_state_anchored
|
| 25 |
+
[summary] {"name": "steps32_c128_mtpost_t1p25_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 128.0, "temp_start": 1.25, "temp_end": 1.25, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 132.59276083128742, "sample_entropy": 4.559239875423023, "distinct_1": 0.05767822265625, "distinct_2": 0.4616477272727273, "top_token_mass": 0.0916290283203125, "tokens_scored": 57001, "readability_score": 4.848120117898956, "mean_chars": 3095.28125, "replacement_chars": 0.0}
|
| 26 |
+
[decode] steps32_c192_mtpost_t1p15_tpow1p0_noise0_state_anchored
|
| 27 |
+
[summary] {"name": "steps32_c192_mtpost_t1p15_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 192.0, "temp_start": 1.15, "temp_end": 1.15, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 79.75199343220605, "sample_entropy": 4.116014300363699, "distinct_1": 0.0526123046875, "distinct_2": 0.37208272238514173, "top_token_mass": 0.182861328125, "tokens_scored": 52336, "readability_score": 4.568094566086867, "mean_chars": 3219.328125, "replacement_chars": 0.0}
|
| 28 |
+
[decode] steps32_c192_mtpost_t1p2_tpow1p0_noise0_state_anchored
|
| 29 |
+
[summary] {"name": "steps32_c192_mtpost_t1p2_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 192.0, "temp_start": 1.2, "temp_end": 1.2, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 87.63682490534464, "sample_entropy": 4.297251891850898, "distinct_1": 0.054412841796875, "distinct_2": 0.4047073558162268, "top_token_mass": 0.1365203857421875, "tokens_scored": 55045, "readability_score": 4.618896624567134, "mean_chars": 3343.125, "replacement_chars": 0.0}
|
| 30 |
+
[decode] steps32_c192_mtpost_t1p25_tpow1p0_noise0_state_anchored
|
| 31 |
+
[summary] {"name": "steps32_c192_mtpost_t1p25_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 192.0, "temp_start": 1.25, "temp_end": 1.25, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 116.21517241972205, "sample_entropy": 4.506314288940267, "distinct_1": 0.0568389892578125, "distinct_2": 0.44780975073313783, "top_token_mass": 0.101043701171875, "tokens_scored": 56746, "readability_score": 4.834847720277795, "mean_chars": 3265.265625, "replacement_chars": 0.0}
|
| 32 |
+
[decode] steps32_c256_mtpost_t1p15_tpow1p0_noise0_state_anchored
|
| 33 |
+
[summary] {"name": "steps32_c256_mtpost_t1p15_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 256.0, "temp_start": 1.15, "temp_end": 1.15, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 71.23326374591926, "sample_entropy": 4.056456480759734, "distinct_1": 0.04852294921875, "distinct_2": 0.35696175464320623, "top_token_mass": 0.1811981201171875, "tokens_scored": 52408, "readability_score": 4.507317547560852, "mean_chars": 3232.96875, "replacement_chars": 0.0}
|
| 34 |
+
[decode] steps32_c256_mtpost_t1p2_tpow1p0_noise0_state_anchored
|
| 35 |
+
[summary] {"name": "steps32_c256_mtpost_t1p2_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 256.0, "temp_start": 1.2, "temp_end": 1.2, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 80.57856411170884, "sample_entropy": 4.252087418800223, "distinct_1": 0.0537109375, "distinct_2": 0.3979258308895406, "top_token_mass": 0.1309356689453125, "tokens_scored": 55459, "readability_score": 4.567108589413614, "mean_chars": 3418.0625, "replacement_chars": 0.0}
|
| 36 |
+
[decode] steps32_c256_mtpost_t1p25_tpow1p0_noise0_state_anchored
|
| 37 |
+
[summary] {"name": "steps32_c256_mtpost_t1p25_tpow1p0_noise0_state_anchored", "step": 119000, "n_samples": 64, "steps": 32, "concentration_max": 256.0, "temp_start": 1.25, "temp_end": 1.25, "temp_schedule": "const", "t_power": 1.0, "eta0": 0.0, "eta_schedule": "none", "noise_conc": 1.0, "final_from": "state", "final_decode": "argmax", "final_temp": 1.0, "final_top_k": 0, "final_uncertain_threshold": 0.85, "update_rule": "anchored", "model_t_mode": "post", "lock_bos": true, "lock_final_eos": false, "detok_genppl": 96.34182099786459, "sample_entropy": 4.457003351165028, "distinct_1": 0.053924560546875, "distinct_2": 0.4288245356793744, "top_token_mass": 0.1002349853515625, "tokens_scored": 57271, "readability_score": 4.673838825132707, "mean_chars": 3389.4375, "replacement_chars": 0.0}
|
LTA_openwebtext_dualt/logs/smoke_duo_aligned_1gpu_b64_metricsbf16.log
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"device": "cuda:0",
|
| 3 |
+
"rank": 0,
|
| 4 |
+
"world_size": 1,
|
| 5 |
+
"samples": "wrapped_streaming",
|
| 6 |
+
"vocab_size": 50257,
|
| 7 |
+
"save_dir": "runs/smoke_duo_aligned_1gpu_b64_metricsbf16",
|
| 8 |
+
"batch_size": 64,
|
| 9 |
+
"grad_accum": 1,
|
| 10 |
+
"effective_batch_size": 64,
|
| 11 |
+
"global_batch_size": 64,
|
| 12 |
+
"lr_schedule": "constant_warmup",
|
| 13 |
+
"warmup_steps": 2500,
|
| 14 |
+
"adam_beta1": 0.9,
|
| 15 |
+
"adam_beta2": 0.999,
|
| 16 |
+
"adam_eps": 1e-08,
|
| 17 |
+
"model_type": "ddit",
|
| 18 |
+
"dual_t": true,
|
| 19 |
+
"corrupt_t_mode": "independent",
|
| 20 |
+
"corrupt_min_t": 0.0,
|
| 21 |
+
"corrupt_max_t": 1.0,
|
| 22 |
+
"torch_compile": false,
|
| 23 |
+
"compile_mode": "max-autotune",
|
| 24 |
+
"state_format": "prob",
|
| 25 |
+
"target_loss": "soft_ce",
|
| 26 |
+
"meanflow_weight": 0.0,
|
| 27 |
+
"bridge_noise_init": "logistic_normal",
|
| 28 |
+
"noise_sigma": -1.0,
|
| 29 |
+
"wrap": true,
|
| 30 |
+
"openwebtext_split": "train_minus_100k",
|
| 31 |
+
"num_workers": 4
|
| 32 |
+
}
|
| 33 |
+
Traceback (most recent call last):
|
| 34 |
+
File "/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/train.py", line 473, in <module>
|
| 35 |
+
main()
|
| 36 |
+
File "/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/train.py", line 402, in main
|
| 37 |
+
raw_loss = masked_soft_ce(logits, bridge.target_probs, bridge.corrupt_mask)
|
| 38 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 39 |
+
File "/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/flowtext_lab/metrics.py", line 19, in masked_soft_ce
|
| 40 |
+
log_probs = F.log_softmax(logits, dim=-1)
|
| 41 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 42 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/nn/functional.py", line 2248, in log_softmax
|
| 43 |
+
ret = input.log_softmax(dim)
|
| 44 |
+
^^^^^^^^^^^^^^^^^^^^^^
|
| 45 |
+
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 12.27 GiB. GPU 0 has a total capacity of 95.22 GiB of which 8.18 GiB is free. Process 351023 has 87.04 GiB memory in use. Of the allocated memory 83.42 GiB is allocated by PyTorch, and 3.19 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
|
| 46 |
+
E0428 23:04:38.584000 293486 torch/distributed/elastic/multiprocessing/api.py:870] failed (exitcode: 1) local_rank: 0 (pid: 293553) of binary: /usr/bin/python
|
| 47 |
+
Traceback (most recent call last):
|
| 48 |
+
File "<frozen runpy>", line 198, in _run_module_as_main
|
| 49 |
+
File "<frozen runpy>", line 88, in _run_code
|
| 50 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/distributed/run.py", line 922, in <module>
|
| 51 |
+
main()
|
| 52 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 355, in wrapper
|
| 53 |
+
return f(*args, **kwargs)
|
| 54 |
+
^^^^^^^^^^^^^^^^^^
|
| 55 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/distributed/run.py", line 918, in main
|
| 56 |
+
run(args)
|
| 57 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/distributed/run.py", line 909, in run
|
| 58 |
+
elastic_launch(
|
| 59 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/distributed/launcher/api.py", line 139, in __call__
|
| 60 |
+
return launch_agent(self._config, self._entrypoint, list(args))
|
| 61 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 62 |
+
File "/usr/local/lib/python3.12/dist-packages/torch/distributed/launcher/api.py", line 270, in launch_agent
|
| 63 |
+
raise ChildFailedError(
|
| 64 |
+
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
|
| 65 |
+
============================================================
|
| 66 |
+
train.py FAILED
|
| 67 |
+
------------------------------------------------------------
|
| 68 |
+
Failures:
|
| 69 |
+
<NO_OTHER_FAILURES>
|
| 70 |
+
------------------------------------------------------------
|
| 71 |
+
Root Cause (first observed failure):
|
| 72 |
+
[0]:
|
| 73 |
+
time : 2026-04-28_23:04:38
|
| 74 |
+
host : localhost
|
| 75 |
+
rank : 0 (local_rank: 0)
|
| 76 |
+
exitcode : 1 (pid: 293553)
|
| 77 |
+
error_file: <N/A>
|
| 78 |
+
traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
|
| 79 |
+
============================================================
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/mixed/foo_fixed.f90
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module foo_fixed
|
| 2 |
+
contains
|
| 3 |
+
subroutine bar12(a)
|
| 4 |
+
!f2py intent(out) a
|
| 5 |
+
integer a
|
| 6 |
+
a = 12
|
| 7 |
+
end subroutine bar12
|
| 8 |
+
end module foo_fixed
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_logical/foo77.f
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function t0(value)
|
| 2 |
+
logical value
|
| 3 |
+
logical t0
|
| 4 |
+
t0 = value
|
| 5 |
+
end
|
| 6 |
+
function t1(value)
|
| 7 |
+
logical*1 value
|
| 8 |
+
logical*1 t1
|
| 9 |
+
t1 = value
|
| 10 |
+
end
|
| 11 |
+
function t2(value)
|
| 12 |
+
logical*2 value
|
| 13 |
+
logical*2 t2
|
| 14 |
+
t2 = value
|
| 15 |
+
end
|
| 16 |
+
function t4(value)
|
| 17 |
+
logical*4 value
|
| 18 |
+
logical*4 t4
|
| 19 |
+
t4 = value
|
| 20 |
+
end
|
| 21 |
+
c function t8(value)
|
| 22 |
+
c logical*8 value
|
| 23 |
+
c logical*8 t8
|
| 24 |
+
c t8 = value
|
| 25 |
+
c end
|
| 26 |
+
|
| 27 |
+
subroutine s0(t0,value)
|
| 28 |
+
logical value
|
| 29 |
+
logical t0
|
| 30 |
+
cf2py intent(out) t0
|
| 31 |
+
t0 = value
|
| 32 |
+
end
|
| 33 |
+
subroutine s1(t1,value)
|
| 34 |
+
logical*1 value
|
| 35 |
+
logical*1 t1
|
| 36 |
+
cf2py intent(out) t1
|
| 37 |
+
t1 = value
|
| 38 |
+
end
|
| 39 |
+
subroutine s2(t2,value)
|
| 40 |
+
logical*2 value
|
| 41 |
+
logical*2 t2
|
| 42 |
+
cf2py intent(out) t2
|
| 43 |
+
t2 = value
|
| 44 |
+
end
|
| 45 |
+
subroutine s4(t4,value)
|
| 46 |
+
logical*4 value
|
| 47 |
+
logical*4 t4
|
| 48 |
+
cf2py intent(out) t4
|
| 49 |
+
t4 = value
|
| 50 |
+
end
|
| 51 |
+
c subroutine s8(t8,value)
|
| 52 |
+
c logical*8 value
|
| 53 |
+
c logical*8 t8
|
| 54 |
+
cf2py intent(out) t8
|
| 55 |
+
c t8 = value
|
| 56 |
+
c end
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_logical/foo90.f90
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module f90_return_logical
|
| 2 |
+
contains
|
| 3 |
+
function t0(value)
|
| 4 |
+
logical :: value
|
| 5 |
+
logical :: t0
|
| 6 |
+
t0 = value
|
| 7 |
+
end function t0
|
| 8 |
+
function t1(value)
|
| 9 |
+
logical(kind=1) :: value
|
| 10 |
+
logical(kind=1) :: t1
|
| 11 |
+
t1 = value
|
| 12 |
+
end function t1
|
| 13 |
+
function t2(value)
|
| 14 |
+
logical(kind=2) :: value
|
| 15 |
+
logical(kind=2) :: t2
|
| 16 |
+
t2 = value
|
| 17 |
+
end function t2
|
| 18 |
+
function t4(value)
|
| 19 |
+
logical(kind=4) :: value
|
| 20 |
+
logical(kind=4) :: t4
|
| 21 |
+
t4 = value
|
| 22 |
+
end function t4
|
| 23 |
+
function t8(value)
|
| 24 |
+
logical(kind=8) :: value
|
| 25 |
+
logical(kind=8) :: t8
|
| 26 |
+
t8 = value
|
| 27 |
+
end function t8
|
| 28 |
+
|
| 29 |
+
subroutine s0(t0,value)
|
| 30 |
+
logical :: value
|
| 31 |
+
logical :: t0
|
| 32 |
+
!f2py intent(out) t0
|
| 33 |
+
t0 = value
|
| 34 |
+
end subroutine s0
|
| 35 |
+
subroutine s1(t1,value)
|
| 36 |
+
logical(kind=1) :: value
|
| 37 |
+
logical(kind=1) :: t1
|
| 38 |
+
!f2py intent(out) t1
|
| 39 |
+
t1 = value
|
| 40 |
+
end subroutine s1
|
| 41 |
+
subroutine s2(t2,value)
|
| 42 |
+
logical(kind=2) :: value
|
| 43 |
+
logical(kind=2) :: t2
|
| 44 |
+
!f2py intent(out) t2
|
| 45 |
+
t2 = value
|
| 46 |
+
end subroutine s2
|
| 47 |
+
subroutine s4(t4,value)
|
| 48 |
+
logical(kind=4) :: value
|
| 49 |
+
logical(kind=4) :: t4
|
| 50 |
+
!f2py intent(out) t4
|
| 51 |
+
t4 = value
|
| 52 |
+
end subroutine s4
|
| 53 |
+
subroutine s8(t8,value)
|
| 54 |
+
logical(kind=8) :: value
|
| 55 |
+
logical(kind=8) :: t8
|
| 56 |
+
!f2py intent(out) t8
|
| 57 |
+
t8 = value
|
| 58 |
+
end subroutine s8
|
| 59 |
+
end module f90_return_logical
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_real/foo77.f
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function t0(value)
|
| 2 |
+
real value
|
| 3 |
+
real t0
|
| 4 |
+
t0 = value
|
| 5 |
+
end
|
| 6 |
+
function t4(value)
|
| 7 |
+
real*4 value
|
| 8 |
+
real*4 t4
|
| 9 |
+
t4 = value
|
| 10 |
+
end
|
| 11 |
+
function t8(value)
|
| 12 |
+
real*8 value
|
| 13 |
+
real*8 t8
|
| 14 |
+
t8 = value
|
| 15 |
+
end
|
| 16 |
+
function td(value)
|
| 17 |
+
double precision value
|
| 18 |
+
double precision td
|
| 19 |
+
td = value
|
| 20 |
+
end
|
| 21 |
+
|
| 22 |
+
subroutine s0(t0,value)
|
| 23 |
+
real value
|
| 24 |
+
real t0
|
| 25 |
+
cf2py intent(out) t0
|
| 26 |
+
t0 = value
|
| 27 |
+
end
|
| 28 |
+
subroutine s4(t4,value)
|
| 29 |
+
real*4 value
|
| 30 |
+
real*4 t4
|
| 31 |
+
cf2py intent(out) t4
|
| 32 |
+
t4 = value
|
| 33 |
+
end
|
| 34 |
+
subroutine s8(t8,value)
|
| 35 |
+
real*8 value
|
| 36 |
+
real*8 t8
|
| 37 |
+
cf2py intent(out) t8
|
| 38 |
+
t8 = value
|
| 39 |
+
end
|
| 40 |
+
subroutine sd(td,value)
|
| 41 |
+
double precision value
|
| 42 |
+
double precision td
|
| 43 |
+
cf2py intent(out) td
|
| 44 |
+
td = value
|
| 45 |
+
end
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/f2py/tests/src/return_real/foo90.f90
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module f90_return_real
|
| 2 |
+
contains
|
| 3 |
+
function t0(value)
|
| 4 |
+
real :: value
|
| 5 |
+
real :: t0
|
| 6 |
+
t0 = value
|
| 7 |
+
end function t0
|
| 8 |
+
function t4(value)
|
| 9 |
+
real(kind=4) :: value
|
| 10 |
+
real(kind=4) :: t4
|
| 11 |
+
t4 = value
|
| 12 |
+
end function t4
|
| 13 |
+
function t8(value)
|
| 14 |
+
real(kind=8) :: value
|
| 15 |
+
real(kind=8) :: t8
|
| 16 |
+
t8 = value
|
| 17 |
+
end function t8
|
| 18 |
+
function td(value)
|
| 19 |
+
double precision :: value
|
| 20 |
+
double precision :: td
|
| 21 |
+
td = value
|
| 22 |
+
end function td
|
| 23 |
+
|
| 24 |
+
subroutine s0(t0,value)
|
| 25 |
+
real :: value
|
| 26 |
+
real :: t0
|
| 27 |
+
!f2py intent(out) t0
|
| 28 |
+
t0 = value
|
| 29 |
+
end subroutine s0
|
| 30 |
+
subroutine s4(t4,value)
|
| 31 |
+
real(kind=4) :: value
|
| 32 |
+
real(kind=4) :: t4
|
| 33 |
+
!f2py intent(out) t4
|
| 34 |
+
t4 = value
|
| 35 |
+
end subroutine s4
|
| 36 |
+
subroutine s8(t8,value)
|
| 37 |
+
real(kind=8) :: value
|
| 38 |
+
real(kind=8) :: t8
|
| 39 |
+
!f2py intent(out) t8
|
| 40 |
+
t8 = value
|
| 41 |
+
end subroutine s8
|
| 42 |
+
subroutine sd(td,value)
|
| 43 |
+
double precision :: value
|
| 44 |
+
double precision :: td
|
| 45 |
+
!f2py intent(out) td
|
| 46 |
+
td = value
|
| 47 |
+
end subroutine sd
|
| 48 |
+
end module f90_return_real
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ctrl/configuration_ctrl.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 Salesforce and HuggingFace Inc. team.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Salesforce CTRL configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="Salesforce/ctrl")
|
| 23 |
+
@strict
|
| 24 |
+
class CTRLConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
dff (`int`, *optional*, defaults to 8192):
|
| 27 |
+
Dimensionality of the inner dimension of the feed forward networks (FFN).
|
| 28 |
+
|
| 29 |
+
Examples:
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
>>> from transformers import CTRLConfig, CTRLModel
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a CTRL configuration
|
| 35 |
+
>>> configuration = CTRLConfig()
|
| 36 |
+
|
| 37 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 38 |
+
>>> model = CTRLModel(configuration)
|
| 39 |
+
|
| 40 |
+
>>> # Accessing the model configuration
|
| 41 |
+
>>> configuration = model.config
|
| 42 |
+
```"""
|
| 43 |
+
|
| 44 |
+
model_type = "ctrl"
|
| 45 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 46 |
+
attribute_map = {
|
| 47 |
+
"max_position_embeddings": "n_positions",
|
| 48 |
+
"hidden_size": "n_embd",
|
| 49 |
+
"num_attention_heads": "n_head",
|
| 50 |
+
"num_hidden_layers": "n_layer",
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
vocab_size: int = 246534
|
| 54 |
+
n_positions: int = 256
|
| 55 |
+
n_embd: int = 1280
|
| 56 |
+
dff: int = 8192
|
| 57 |
+
n_layer: int = 48
|
| 58 |
+
n_head: int = 16
|
| 59 |
+
resid_pdrop: float | int = 0.1
|
| 60 |
+
embd_pdrop: float | int = 0.1
|
| 61 |
+
layer_norm_epsilon: float = 1e-6
|
| 62 |
+
initializer_range: float = 0.02
|
| 63 |
+
use_cache: bool = True
|
| 64 |
+
pad_token_id: int | None = None
|
| 65 |
+
bos_token_id: int | None = None
|
| 66 |
+
eos_token_id: int | list[int] | None = None
|
| 67 |
+
tie_word_embeddings: bool = True
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
__all__ = ["CTRLConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ctrl/modeling_ctrl.py
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 Salesforce and HuggingFace Inc. team.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch CTRL model."""
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 21 |
+
|
| 22 |
+
from ... import initialization as init
|
| 23 |
+
from ...cache_utils import Cache, DynamicCache
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutput
|
| 26 |
+
from ...modeling_utils import PreTrainedModel
|
| 27 |
+
from ...utils import (
|
| 28 |
+
auto_docstring,
|
| 29 |
+
logging,
|
| 30 |
+
)
|
| 31 |
+
from .configuration_ctrl import CTRLConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def angle_defn(pos, i, d_model_size):
|
| 38 |
+
angle_rates = 1 / torch.pow(10000, (2 * (i // 2)) / d_model_size)
|
| 39 |
+
return pos * angle_rates
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def positional_encoding(position, d_model_size, dtype):
|
| 43 |
+
# create the sinusoidal pattern for the positional encoding
|
| 44 |
+
angle_rads = angle_defn(
|
| 45 |
+
torch.arange(position, dtype=torch.int64).to(dtype).unsqueeze(1),
|
| 46 |
+
torch.arange(d_model_size, dtype=torch.int64).to(dtype).unsqueeze(0),
|
| 47 |
+
d_model_size,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
sines = torch.sin(angle_rads[:, 0::2])
|
| 51 |
+
cosines = torch.cos(angle_rads[:, 1::2])
|
| 52 |
+
|
| 53 |
+
pos_encoding = torch.cat([sines, cosines], dim=-1)
|
| 54 |
+
return pos_encoding
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def scaled_dot_product_attention(q, k, v, mask, attention_mask=None):
|
| 58 |
+
# calculate attention
|
| 59 |
+
matmul_qk = torch.matmul(q, k.permute(0, 1, 3, 2))
|
| 60 |
+
|
| 61 |
+
dk = k.shape[-1]
|
| 62 |
+
scaled_attention_logits = matmul_qk / np.sqrt(dk)
|
| 63 |
+
|
| 64 |
+
if mask is not None:
|
| 65 |
+
nd, ns = scaled_attention_logits.size(-2), scaled_attention_logits.size(-1)
|
| 66 |
+
scaled_attention_logits += mask[ns - nd : ns, :ns] * -1e4
|
| 67 |
+
|
| 68 |
+
if attention_mask is not None:
|
| 69 |
+
# Apply the attention mask
|
| 70 |
+
scaled_attention_logits = scaled_attention_logits + attention_mask
|
| 71 |
+
|
| 72 |
+
attention_weights = torch.softmax(scaled_attention_logits, dim=-1)
|
| 73 |
+
|
| 74 |
+
output = torch.matmul(attention_weights, v)
|
| 75 |
+
|
| 76 |
+
return output, attention_weights
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class MultiHeadAttention(nn.Module):
|
| 80 |
+
def __init__(self, d_model_size, num_heads, layer_idx=None):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.num_heads = num_heads
|
| 83 |
+
self.d_model_size = d_model_size
|
| 84 |
+
self.layer_idx = layer_idx
|
| 85 |
+
|
| 86 |
+
self.depth = int(d_model_size / self.num_heads)
|
| 87 |
+
|
| 88 |
+
self.Wq = nn.Linear(d_model_size, d_model_size)
|
| 89 |
+
self.Wk = nn.Linear(d_model_size, d_model_size)
|
| 90 |
+
self.Wv = nn.Linear(d_model_size, d_model_size)
|
| 91 |
+
|
| 92 |
+
self.dense = nn.Linear(d_model_size, d_model_size)
|
| 93 |
+
|
| 94 |
+
def split_into_heads(self, x, batch_size):
|
| 95 |
+
x = x.reshape(batch_size, -1, self.num_heads, self.depth)
|
| 96 |
+
return x.permute([0, 2, 1, 3])
|
| 97 |
+
|
| 98 |
+
def forward(
|
| 99 |
+
self,
|
| 100 |
+
v,
|
| 101 |
+
k,
|
| 102 |
+
q,
|
| 103 |
+
mask,
|
| 104 |
+
layer_past=None,
|
| 105 |
+
attention_mask=None,
|
| 106 |
+
use_cache=False,
|
| 107 |
+
output_attentions=False,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
batch_size = q.shape[0]
|
| 111 |
+
|
| 112 |
+
q = self.Wq(q)
|
| 113 |
+
k = self.Wk(k)
|
| 114 |
+
v = self.Wv(v)
|
| 115 |
+
|
| 116 |
+
q = self.split_into_heads(q, batch_size)
|
| 117 |
+
k = self.split_into_heads(k, batch_size)
|
| 118 |
+
v = self.split_into_heads(v, batch_size)
|
| 119 |
+
|
| 120 |
+
if layer_past is not None:
|
| 121 |
+
k, v = layer_past.update(k, v, self.layer_idx)
|
| 122 |
+
|
| 123 |
+
output = scaled_dot_product_attention(q, k, v, mask, attention_mask)
|
| 124 |
+
scaled_attention = output[0].permute([0, 2, 1, 3])
|
| 125 |
+
attn = output[1]
|
| 126 |
+
original_size_attention = scaled_attention.reshape(batch_size, -1, self.d_model_size)
|
| 127 |
+
output = self.dense(original_size_attention)
|
| 128 |
+
return output, attn
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def point_wise_feed_forward_network(d_model_size, dff):
|
| 132 |
+
return nn.Sequential(nn.Linear(d_model_size, dff), nn.ReLU(), nn.Linear(dff, d_model_size))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class EncoderLayer(nn.Module):
|
| 136 |
+
def __init__(self, d_model_size, num_heads, dff, rate=0.1, layer_idx=None):
|
| 137 |
+
super().__init__()
|
| 138 |
+
|
| 139 |
+
self.multi_head_attention = MultiHeadAttention(d_model_size, num_heads, layer_idx=layer_idx)
|
| 140 |
+
self.ffn = point_wise_feed_forward_network(d_model_size, dff)
|
| 141 |
+
|
| 142 |
+
self.layernorm1 = nn.LayerNorm(d_model_size, eps=1e-6)
|
| 143 |
+
self.layernorm2 = nn.LayerNorm(d_model_size, eps=1e-6)
|
| 144 |
+
|
| 145 |
+
self.dropout1 = nn.Dropout(rate)
|
| 146 |
+
self.dropout2 = nn.Dropout(rate)
|
| 147 |
+
|
| 148 |
+
def forward(
|
| 149 |
+
self,
|
| 150 |
+
x,
|
| 151 |
+
mask,
|
| 152 |
+
layer_past=None,
|
| 153 |
+
attention_mask=None,
|
| 154 |
+
use_cache=False,
|
| 155 |
+
output_attentions=False,
|
| 156 |
+
**kwargs,
|
| 157 |
+
):
|
| 158 |
+
normed = self.layernorm1(x)
|
| 159 |
+
attn_outputs = self.multi_head_attention(
|
| 160 |
+
normed,
|
| 161 |
+
normed,
|
| 162 |
+
normed,
|
| 163 |
+
mask,
|
| 164 |
+
layer_past=layer_past,
|
| 165 |
+
attention_mask=attention_mask,
|
| 166 |
+
use_cache=use_cache,
|
| 167 |
+
output_attentions=output_attentions,
|
| 168 |
+
)
|
| 169 |
+
attn_output = attn_outputs[0]
|
| 170 |
+
attn_output = self.dropout1(attn_output)
|
| 171 |
+
out1 = x + attn_output
|
| 172 |
+
|
| 173 |
+
out2 = self.layernorm2(out1)
|
| 174 |
+
ffn_output = self.ffn(out2)
|
| 175 |
+
ffn_output = self.dropout2(ffn_output)
|
| 176 |
+
out2 = out1 + ffn_output
|
| 177 |
+
|
| 178 |
+
outputs = (out2,) + attn_outputs[1:]
|
| 179 |
+
return outputs
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@auto_docstring
|
| 183 |
+
class CTRLPreTrainedModel(PreTrainedModel):
|
| 184 |
+
config: CTRLConfig
|
| 185 |
+
base_model_prefix = "transformer"
|
| 186 |
+
|
| 187 |
+
def _init_weights(self, module):
|
| 188 |
+
super()._init_weights(module)
|
| 189 |
+
if isinstance(module, CTRLModel):
|
| 190 |
+
init.copy_(
|
| 191 |
+
module.pos_encoding, positional_encoding(module.config.n_positions, module.d_model_size, torch.float)
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@auto_docstring
|
| 196 |
+
class CTRLModel(CTRLPreTrainedModel):
|
| 197 |
+
def __init__(self, config):
|
| 198 |
+
super().__init__(config)
|
| 199 |
+
|
| 200 |
+
self.d_model_size = config.n_embd
|
| 201 |
+
self.num_layers = config.n_layer
|
| 202 |
+
|
| 203 |
+
self.w = nn.Embedding(config.vocab_size, config.n_embd)
|
| 204 |
+
|
| 205 |
+
self.dropout = nn.Dropout(config.embd_pdrop)
|
| 206 |
+
self.h = nn.ModuleList(
|
| 207 |
+
[
|
| 208 |
+
EncoderLayer(config.n_embd, config.n_head, config.dff, config.resid_pdrop, layer_idx=i)
|
| 209 |
+
for i in range(config.n_layer)
|
| 210 |
+
]
|
| 211 |
+
)
|
| 212 |
+
self.layernorm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 213 |
+
|
| 214 |
+
self.register_buffer(
|
| 215 |
+
"pos_encoding", positional_encoding(config.n_positions, self.d_model_size, torch.float), persistent=False
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Initialize weights and apply final processing
|
| 219 |
+
self.post_init()
|
| 220 |
+
|
| 221 |
+
def get_input_embeddings(self):
|
| 222 |
+
return self.w
|
| 223 |
+
|
| 224 |
+
def set_input_embeddings(self, new_embeddings):
|
| 225 |
+
self.w = new_embeddings
|
| 226 |
+
|
| 227 |
+
@auto_docstring
|
| 228 |
+
def forward(
|
| 229 |
+
self,
|
| 230 |
+
input_ids: torch.LongTensor | None = None,
|
| 231 |
+
past_key_values: Cache | None = None,
|
| 232 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 233 |
+
token_type_ids: torch.LongTensor | None = None,
|
| 234 |
+
position_ids: torch.LongTensor | None = None,
|
| 235 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 236 |
+
use_cache: bool | None = None,
|
| 237 |
+
output_attentions: bool | None = None,
|
| 238 |
+
output_hidden_states: bool | None = None,
|
| 239 |
+
return_dict: bool | None = None,
|
| 240 |
+
**kwargs, # NOOP kwargs, for now
|
| 241 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPast:
|
| 242 |
+
r"""
|
| 243 |
+
Example:
|
| 244 |
+
|
| 245 |
+
```python
|
| 246 |
+
>>> from transformers import AutoTokenizer, CTRLModel
|
| 247 |
+
>>> import torch
|
| 248 |
+
|
| 249 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 250 |
+
>>> model = CTRLModel.from_pretrained("Salesforce/ctrl")
|
| 251 |
+
|
| 252 |
+
>>> # CTRL was trained with control codes as the first token
|
| 253 |
+
>>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
|
| 254 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 255 |
+
|
| 256 |
+
>>> outputs = model(**inputs)
|
| 257 |
+
|
| 258 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 259 |
+
>>> list(last_hidden_states.shape)
|
| 260 |
+
[1, 5, 1280]
|
| 261 |
+
```"""
|
| 262 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 263 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 264 |
+
output_hidden_states = (
|
| 265 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 266 |
+
)
|
| 267 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 268 |
+
|
| 269 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 270 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 271 |
+
elif input_ids is not None:
|
| 272 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 273 |
+
input_shape = input_ids.size()
|
| 274 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 275 |
+
batch_size = input_ids.shape[0]
|
| 276 |
+
elif inputs_embeds is not None:
|
| 277 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 278 |
+
batch_size = inputs_embeds.shape[0]
|
| 279 |
+
else:
|
| 280 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 281 |
+
|
| 282 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 283 |
+
|
| 284 |
+
if use_cache and past_key_values is None:
|
| 285 |
+
past_key_values = DynamicCache(config=self.config)
|
| 286 |
+
|
| 287 |
+
past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 288 |
+
if position_ids is None:
|
| 289 |
+
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
|
| 290 |
+
position_ids = position_ids.unsqueeze(0)
|
| 291 |
+
|
| 292 |
+
# Attention mask.
|
| 293 |
+
if attention_mask is not None:
|
| 294 |
+
if batch_size <= 0:
|
| 295 |
+
raise ValueError("batch_size has to be defined and > 0")
|
| 296 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
| 297 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 298 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 299 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 300 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 301 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 302 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 303 |
+
|
| 304 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 305 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 306 |
+
# positions we want to attend and the dtype's smallest value for masked positions.
|
| 307 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 308 |
+
# effectively the same as removing these entirely.
|
| 309 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
| 310 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
| 311 |
+
|
| 312 |
+
if token_type_ids is not None:
|
| 313 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
| 314 |
+
token_type_embeds = self.w(token_type_ids)
|
| 315 |
+
token_type_embeds *= np.sqrt(self.d_model_size)
|
| 316 |
+
else:
|
| 317 |
+
token_type_embeds = 0
|
| 318 |
+
|
| 319 |
+
if inputs_embeds is None:
|
| 320 |
+
inputs_embeds = self.w(input_ids)
|
| 321 |
+
# inputs_embeds = embedded.unsqueeze(0) if len(input_ids.shape)<2 else embedded
|
| 322 |
+
seq_len = input_shape[-1]
|
| 323 |
+
mask = torch.triu(torch.ones(seq_len + past_length, seq_len + past_length), 1).to(device)
|
| 324 |
+
|
| 325 |
+
inputs_embeds *= np.sqrt(self.d_model_size)
|
| 326 |
+
|
| 327 |
+
# `self.pos_encoding` won't be sent to the correct device along the model, so we do it manually.
|
| 328 |
+
self.pos_encoding = self.pos_encoding.to(device)
|
| 329 |
+
pos_embeds = self.pos_encoding[position_ids, :]
|
| 330 |
+
|
| 331 |
+
hidden_states = inputs_embeds + pos_embeds + token_type_embeds
|
| 332 |
+
|
| 333 |
+
hidden_states = self.dropout(hidden_states)
|
| 334 |
+
|
| 335 |
+
all_hidden_states = () if output_hidden_states else None
|
| 336 |
+
all_attentions = () if output_attentions else None
|
| 337 |
+
for i, h in enumerate(self.h):
|
| 338 |
+
if output_hidden_states:
|
| 339 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 340 |
+
outputs = h(
|
| 341 |
+
hidden_states,
|
| 342 |
+
mask,
|
| 343 |
+
layer_past=past_key_values,
|
| 344 |
+
attention_mask=attention_mask,
|
| 345 |
+
use_cache=use_cache,
|
| 346 |
+
output_attentions=output_attentions,
|
| 347 |
+
)
|
| 348 |
+
hidden_states = outputs[0]
|
| 349 |
+
if output_attentions:
|
| 350 |
+
all_attentions += (outputs[1],)
|
| 351 |
+
|
| 352 |
+
hidden_states = self.layernorm(hidden_states)
|
| 353 |
+
if output_hidden_states:
|
| 354 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 355 |
+
|
| 356 |
+
if not return_dict:
|
| 357 |
+
return tuple(
|
| 358 |
+
v for v in [hidden_states, past_key_values, all_hidden_states, all_attentions] if v is not None
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
return BaseModelOutputWithPast(
|
| 362 |
+
last_hidden_state=hidden_states,
|
| 363 |
+
past_key_values=past_key_values,
|
| 364 |
+
hidden_states=all_hidden_states,
|
| 365 |
+
attentions=all_attentions,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@auto_docstring(
|
| 370 |
+
custom_intro="""
|
| 371 |
+
The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 372 |
+
embeddings).
|
| 373 |
+
"""
|
| 374 |
+
)
|
| 375 |
+
class CTRLLMHeadModel(CTRLPreTrainedModel, GenerationMixin):
|
| 376 |
+
_tied_weights_keys = {"lm_head.weight": "transformer.w.weight"}
|
| 377 |
+
|
| 378 |
+
def __init__(self, config):
|
| 379 |
+
super().__init__(config)
|
| 380 |
+
self.transformer = CTRLModel(config)
|
| 381 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=True)
|
| 382 |
+
|
| 383 |
+
# Initialize weights and apply final processing
|
| 384 |
+
self.post_init()
|
| 385 |
+
|
| 386 |
+
@auto_docstring
|
| 387 |
+
def forward(
|
| 388 |
+
self,
|
| 389 |
+
input_ids: torch.LongTensor | None = None,
|
| 390 |
+
past_key_values: Cache | None = None,
|
| 391 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 392 |
+
token_type_ids: torch.LongTensor | None = None,
|
| 393 |
+
position_ids: torch.LongTensor | None = None,
|
| 394 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 395 |
+
labels: torch.LongTensor | None = None,
|
| 396 |
+
use_cache: bool | None = None,
|
| 397 |
+
output_attentions: bool | None = None,
|
| 398 |
+
output_hidden_states: bool | None = None,
|
| 399 |
+
return_dict: bool | None = None,
|
| 400 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 401 |
+
**kwargs,
|
| 402 |
+
) -> tuple[torch.Tensor] | CausalLMOutputWithPast:
|
| 403 |
+
r"""
|
| 404 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 405 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 406 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 407 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 408 |
+
|
| 409 |
+
Example:
|
| 410 |
+
|
| 411 |
+
```python
|
| 412 |
+
>>> import torch
|
| 413 |
+
>>> from transformers import AutoTokenizer, CTRLLMHeadModel
|
| 414 |
+
|
| 415 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 416 |
+
>>> model = CTRLLMHeadModel.from_pretrained("Salesforce/ctrl")
|
| 417 |
+
|
| 418 |
+
>>> # CTRL was trained with control codes as the first token
|
| 419 |
+
>>> inputs = tokenizer("Wikipedia The llama is", return_tensors="pt")
|
| 420 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 421 |
+
|
| 422 |
+
>>> sequence_ids = model.generate(inputs["input_ids"])
|
| 423 |
+
>>> sequences = tokenizer.batch_decode(sequence_ids)
|
| 424 |
+
>>> sequences
|
| 425 |
+
['Wikipedia The llama is a member of the family Bovidae. It is native to the Andes of Peru,']
|
| 426 |
+
|
| 427 |
+
>>> outputs = model(**inputs, labels=inputs["input_ids"])
|
| 428 |
+
>>> round(outputs.loss.item(), 2)
|
| 429 |
+
9.21
|
| 430 |
+
|
| 431 |
+
>>> list(outputs.logits.shape)
|
| 432 |
+
[1, 5, 246534]
|
| 433 |
+
```"""
|
| 434 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 435 |
+
|
| 436 |
+
transformer_outputs = self.transformer(
|
| 437 |
+
input_ids,
|
| 438 |
+
past_key_values=past_key_values,
|
| 439 |
+
attention_mask=attention_mask,
|
| 440 |
+
token_type_ids=token_type_ids,
|
| 441 |
+
position_ids=position_ids,
|
| 442 |
+
inputs_embeds=inputs_embeds,
|
| 443 |
+
use_cache=use_cache,
|
| 444 |
+
output_attentions=output_attentions,
|
| 445 |
+
output_hidden_states=output_hidden_states,
|
| 446 |
+
return_dict=return_dict,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
hidden_states = transformer_outputs[0]
|
| 450 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 451 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 452 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 453 |
+
|
| 454 |
+
loss = None
|
| 455 |
+
if labels is not None:
|
| 456 |
+
loss = self.loss_function(
|
| 457 |
+
logits,
|
| 458 |
+
labels,
|
| 459 |
+
vocab_size=self.config.vocab_size,
|
| 460 |
+
**kwargs,
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
if not return_dict:
|
| 464 |
+
output = (logits,) + transformer_outputs[1:]
|
| 465 |
+
return ((loss,) + output) if loss is not None else output
|
| 466 |
+
|
| 467 |
+
return CausalLMOutputWithPast(
|
| 468 |
+
loss=loss,
|
| 469 |
+
logits=logits,
|
| 470 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 471 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 472 |
+
attentions=transformer_outputs.attentions,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
def prepare_inputs_for_generation(
|
| 476 |
+
self, input_ids, past_key_values=None, use_cache=None, is_first_iteration=False, **kwargs
|
| 477 |
+
):
|
| 478 |
+
# Overwritten -- `token_type_ids` are created in custom way inside model`
|
| 479 |
+
|
| 480 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 481 |
+
input_ids,
|
| 482 |
+
past_key_values=past_key_values,
|
| 483 |
+
use_cache=use_cache,
|
| 484 |
+
is_first_iteration=is_first_iteration,
|
| 485 |
+
**kwargs,
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# token_type_ids are computed on CTRLModel.forward()
|
| 489 |
+
model_inputs.pop("token_type_ids", None)
|
| 490 |
+
|
| 491 |
+
return model_inputs
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
@auto_docstring(
|
| 495 |
+
custom_intro="""
|
| 496 |
+
The CTRL Model transformer with a sequence classification head on top (linear layer).
|
| 497 |
+
[`CTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 498 |
+
(e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last
|
| 499 |
+
token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in
|
| 500 |
+
each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
|
| 501 |
+
guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last
|
| 502 |
+
value in each row of the batch).
|
| 503 |
+
"""
|
| 504 |
+
)
|
| 505 |
+
class CTRLForSequenceClassification(CTRLPreTrainedModel):
|
| 506 |
+
def __init__(self, config):
|
| 507 |
+
super().__init__(config)
|
| 508 |
+
self.num_labels = config.num_labels
|
| 509 |
+
self.transformer = CTRLModel(config)
|
| 510 |
+
self.classifier = nn.Linear(config.n_embd, self.num_labels, bias=False)
|
| 511 |
+
|
| 512 |
+
# Initialize weights and apply final processing
|
| 513 |
+
self.post_init()
|
| 514 |
+
|
| 515 |
+
@auto_docstring
|
| 516 |
+
def forward(
|
| 517 |
+
self,
|
| 518 |
+
input_ids: torch.LongTensor | None = None,
|
| 519 |
+
past_key_values: Cache | None = None,
|
| 520 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 521 |
+
token_type_ids: torch.LongTensor | None = None,
|
| 522 |
+
position_ids: torch.LongTensor | None = None,
|
| 523 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 524 |
+
labels: torch.LongTensor | None = None,
|
| 525 |
+
use_cache: bool | None = None,
|
| 526 |
+
output_attentions: bool | None = None,
|
| 527 |
+
output_hidden_states: bool | None = None,
|
| 528 |
+
return_dict: bool | None = None,
|
| 529 |
+
**kwargs,
|
| 530 |
+
) -> tuple[torch.Tensor] | SequenceClassifierOutput:
|
| 531 |
+
r"""
|
| 532 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 533 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 534 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 535 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 536 |
+
|
| 537 |
+
Example of single-label classification:
|
| 538 |
+
|
| 539 |
+
```python
|
| 540 |
+
>>> import torch
|
| 541 |
+
>>> from transformers import AutoTokenizer, CTRLForSequenceClassification
|
| 542 |
+
|
| 543 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 544 |
+
>>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl")
|
| 545 |
+
|
| 546 |
+
>>> # CTRL was trained with control codes as the first token
|
| 547 |
+
>>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
|
| 548 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 549 |
+
|
| 550 |
+
>>> with torch.no_grad():
|
| 551 |
+
... logits = model(**inputs).logits
|
| 552 |
+
|
| 553 |
+
>>> predicted_class_id = logits.argmax().item()
|
| 554 |
+
>>> model.config.id2label[predicted_class_id]
|
| 555 |
+
'LABEL_0'
|
| 556 |
+
```
|
| 557 |
+
|
| 558 |
+
```python
|
| 559 |
+
>>> import torch
|
| 560 |
+
|
| 561 |
+
>>> torch.manual_seed(42) # doctest: +IGNORE_RESULT
|
| 562 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 563 |
+
>>> num_labels = len(model.config.id2label)
|
| 564 |
+
>>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
|
| 565 |
+
|
| 566 |
+
>>> labels = torch.tensor(1)
|
| 567 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 568 |
+
>>> round(loss.item(), 2)
|
| 569 |
+
0.93
|
| 570 |
+
```
|
| 571 |
+
|
| 572 |
+
Example of multi-label classification:
|
| 573 |
+
|
| 574 |
+
```python
|
| 575 |
+
>>> import torch
|
| 576 |
+
>>> from transformers import AutoTokenizer, CTRLForSequenceClassification
|
| 577 |
+
|
| 578 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 579 |
+
>>> model = CTRLForSequenceClassification.from_pretrained(
|
| 580 |
+
... "Salesforce/ctrl", problem_type="multi_label_classification"
|
| 581 |
+
... )
|
| 582 |
+
|
| 583 |
+
>>> # CTRL was trained with control codes as the first token
|
| 584 |
+
>>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
|
| 585 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 586 |
+
|
| 587 |
+
>>> with torch.no_grad():
|
| 588 |
+
... logits = model(**inputs).logits
|
| 589 |
+
|
| 590 |
+
>>> predicted_class_id = logits.argmax().item()
|
| 591 |
+
>>> model.config.id2label[predicted_class_id]
|
| 592 |
+
'LABEL_0'
|
| 593 |
+
```
|
| 594 |
+
|
| 595 |
+
```python
|
| 596 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 597 |
+
>>> num_labels = len(model.config.id2label)
|
| 598 |
+
>>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
|
| 599 |
+
|
| 600 |
+
>>> num_labels = len(model.config.id2label)
|
| 601 |
+
>>> labels = torch.nn.functional.one_hot(torch.tensor([predicted_class_id]), num_classes=num_labels).to(
|
| 602 |
+
... torch.float
|
| 603 |
+
... )
|
| 604 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 605 |
+
>>> loss.backward() # doctest: +IGNORE_RESULT
|
| 606 |
+
```"""
|
| 607 |
+
|
| 608 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 609 |
+
|
| 610 |
+
transformer_outputs = self.transformer(
|
| 611 |
+
input_ids,
|
| 612 |
+
past_key_values=past_key_values,
|
| 613 |
+
attention_mask=attention_mask,
|
| 614 |
+
token_type_ids=token_type_ids,
|
| 615 |
+
position_ids=position_ids,
|
| 616 |
+
inputs_embeds=inputs_embeds,
|
| 617 |
+
use_cache=use_cache,
|
| 618 |
+
output_attentions=output_attentions,
|
| 619 |
+
output_hidden_states=output_hidden_states,
|
| 620 |
+
return_dict=return_dict,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
hidden_states = transformer_outputs[0]
|
| 624 |
+
logits = self.classifier(hidden_states)
|
| 625 |
+
|
| 626 |
+
if input_ids is not None:
|
| 627 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
| 628 |
+
else:
|
| 629 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
| 630 |
+
|
| 631 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 632 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 633 |
+
if self.config.pad_token_id is None:
|
| 634 |
+
last_non_pad_token = -1
|
| 635 |
+
elif input_ids is not None:
|
| 636 |
+
# To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
|
| 637 |
+
non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
|
| 638 |
+
token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
|
| 639 |
+
last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
|
| 640 |
+
else:
|
| 641 |
+
last_non_pad_token = -1
|
| 642 |
+
logger.warning_once(
|
| 643 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 644 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
|
| 648 |
+
|
| 649 |
+
loss = None
|
| 650 |
+
if labels is not None:
|
| 651 |
+
if self.config.problem_type is None:
|
| 652 |
+
if self.num_labels == 1:
|
| 653 |
+
self.config.problem_type = "regression"
|
| 654 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 655 |
+
self.config.problem_type = "single_label_classification"
|
| 656 |
+
else:
|
| 657 |
+
self.config.problem_type = "multi_label_classification"
|
| 658 |
+
|
| 659 |
+
if self.config.problem_type == "regression":
|
| 660 |
+
loss_fct = MSELoss()
|
| 661 |
+
if self.num_labels == 1:
|
| 662 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 663 |
+
else:
|
| 664 |
+
loss = loss_fct(pooled_logits, labels)
|
| 665 |
+
elif self.config.problem_type == "single_label_classification":
|
| 666 |
+
loss_fct = CrossEntropyLoss()
|
| 667 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 668 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 669 |
+
loss_fct = BCEWithLogitsLoss()
|
| 670 |
+
loss = loss_fct(pooled_logits, labels)
|
| 671 |
+
if not return_dict:
|
| 672 |
+
output = (pooled_logits,) + transformer_outputs[2:]
|
| 673 |
+
return ((loss,) + output) if loss is not None else output
|
| 674 |
+
|
| 675 |
+
return SequenceClassifierOutput(
|
| 676 |
+
loss=loss,
|
| 677 |
+
logits=pooled_logits,
|
| 678 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 679 |
+
attentions=transformer_outputs.attentions,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
__all__ = ["CTRLForSequenceClassification", "CTRLLMHeadModel", "CTRLModel", "CTRLPreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/doge/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_doge import *
|
| 22 |
+
from .modeling_doge import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pp_ocrv5_server_det/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_pp_ocrv5_server_det import *
|
| 22 |
+
from .image_processing_pp_ocrv5_server_det import *
|
| 23 |
+
from .modeling_pp_ocrv5_server_det import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pp_ocrv5_server_det/configuration_pp_ocrv5_server_det.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/pp_ocrv5_server_det/modular_pp_ocrv5_server_det.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_pp_ocrv5_server_det.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from huggingface_hub.dataclasses import strict
|
| 22 |
+
|
| 23 |
+
from ...backbone_utils import consolidate_backbone_kwargs_to_config
|
| 24 |
+
from ...configuration_utils import PreTrainedConfig
|
| 25 |
+
from ...utils import auto_docstring
|
| 26 |
+
from ..auto import AutoConfig
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@auto_docstring(checkpoint="PaddlePaddle/PP-OCRv5_server_det_safetensors")
|
| 30 |
+
@strict
|
| 31 |
+
class PPOCRV5ServerDetConfig(PreTrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
interpolate_mode (`str`, *optional*, defaults to `"nearest"`):
|
| 34 |
+
The interpolation mode used for upsampling or downsampling feature maps in the neck network.
|
| 35 |
+
neck_out_channels (`int`, *optional*, defaults to 256):
|
| 36 |
+
The number of output channels from the neck network, responsible for feature fusion and refinement.
|
| 37 |
+
reduce_factor (`int`, *optional*, defaults to 2):
|
| 38 |
+
The channel reduction factor used in the neck blocks to balance performance and complexity.
|
| 39 |
+
intraclass_block_number (`int`, *optional*, defaults to 4):
|
| 40 |
+
The number of Intra-Class Block modules used for enhancing feature representation.
|
| 41 |
+
intraclass_block_config (`dict`, *optional*, defaults to `None`):
|
| 42 |
+
Configuration for the Intra-Class Block modules, if any, used for enhancing feature representation.
|
| 43 |
+
scale_factor (`int`, *optional*, defaults to 2):
|
| 44 |
+
The scaling factor used for spatial resolution adjustments in the feature maps.
|
| 45 |
+
scale_factor_list (`list[int]`, *optional*, defaults to `None`):
|
| 46 |
+
A list of scaling factors used for spatial resolution adjustments in the feature maps.
|
| 47 |
+
kernel_list (`list[int]`, *optional*, defaults to `[3, 2, 2]`):
|
| 48 |
+
The list of kernel sizes for convolutional layers in the head network for multi-scale feature extraction.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
sub_configs = {"backbone_config": AutoConfig}
|
| 52 |
+
model_type = "pp_ocrv5_server_det"
|
| 53 |
+
|
| 54 |
+
interpolate_mode: str = "nearest"
|
| 55 |
+
backbone_config: dict | PreTrainedConfig | None = None
|
| 56 |
+
neck_out_channels: int = 256
|
| 57 |
+
reduce_factor: int = 2
|
| 58 |
+
intraclass_block_number: int = 4
|
| 59 |
+
intraclass_block_config: dict | None = None
|
| 60 |
+
scale_factor: int = 2
|
| 61 |
+
scale_factor_list: list | None = None
|
| 62 |
+
hidden_act: str = "relu"
|
| 63 |
+
kernel_list: list | None = None
|
| 64 |
+
id2label: dict[int, str] | dict[str, str] | None = None
|
| 65 |
+
|
| 66 |
+
def __post_init__(self, **kwargs):
|
| 67 |
+
self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
|
| 68 |
+
backbone_config=self.backbone_config,
|
| 69 |
+
default_config_type="hgnet_v2",
|
| 70 |
+
default_config_kwargs={
|
| 71 |
+
"arch": "L",
|
| 72 |
+
"return_idx": [0, 1, 2, 3],
|
| 73 |
+
"freeze_stem_only": True,
|
| 74 |
+
"freeze_at": 0,
|
| 75 |
+
"freeze_norm": True,
|
| 76 |
+
"lr_mult_list": [0, 0.05, 0.05, 0.05, 0.05],
|
| 77 |
+
"out_features": ["stage1", "stage2", "stage3", "stage4"],
|
| 78 |
+
},
|
| 79 |
+
**kwargs,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# For object detection pipeline compatibility: single class "text"
|
| 83 |
+
self.id2label = {0: "text"} if self.id2label is None else self.id2label
|
| 84 |
+
super().__post_init__(**kwargs)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
__all__ = ["PPOCRV5ServerDetConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pp_ocrv5_server_det/modular_pp_ocrv5_server_det.py
ADDED
|
@@ -0,0 +1,909 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
import torchvision.transforms.v2.functional as tvF
|
| 22 |
+
from huggingface_hub.dataclasses import strict
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...backbone_utils import consolidate_backbone_kwargs_to_config, load_backbone
|
| 26 |
+
from ...configuration_utils import PreTrainedConfig
|
| 27 |
+
from ...feature_extraction_utils import BatchFeature
|
| 28 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 29 |
+
from ...image_transforms import group_images_by_shape, reorder_images
|
| 30 |
+
from ...image_utils import PILImageResampling, SizeDict
|
| 31 |
+
from ...modeling_outputs import BaseModelOutputWithNoAttention
|
| 32 |
+
from ...modeling_utils import PreTrainedModel
|
| 33 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 34 |
+
from ...utils import (
|
| 35 |
+
TransformersKwargs,
|
| 36 |
+
auto_docstring,
|
| 37 |
+
can_return_tuple,
|
| 38 |
+
is_cv2_available,
|
| 39 |
+
logging,
|
| 40 |
+
requires_backends,
|
| 41 |
+
)
|
| 42 |
+
from ...utils.generic import TensorType
|
| 43 |
+
from ...utils.import_utils import requires
|
| 44 |
+
from ..auto import AutoConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if is_cv2_available():
|
| 48 |
+
import cv2
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@auto_docstring(checkpoint="PaddlePaddle/PP-OCRv5_server_det_safetensors")
|
| 55 |
+
@strict
|
| 56 |
+
class PPOCRV5ServerDetConfig(PreTrainedConfig):
|
| 57 |
+
r"""
|
| 58 |
+
interpolate_mode (`str`, *optional*, defaults to `"nearest"`):
|
| 59 |
+
The interpolation mode used for upsampling or downsampling feature maps in the neck network.
|
| 60 |
+
neck_out_channels (`int`, *optional*, defaults to 256):
|
| 61 |
+
The number of output channels from the neck network, responsible for feature fusion and refinement.
|
| 62 |
+
reduce_factor (`int`, *optional*, defaults to 2):
|
| 63 |
+
The channel reduction factor used in the neck blocks to balance performance and complexity.
|
| 64 |
+
intraclass_block_number (`int`, *optional*, defaults to 4):
|
| 65 |
+
The number of Intra-Class Block modules used for enhancing feature representation.
|
| 66 |
+
intraclass_block_config (`dict`, *optional*, defaults to `None`):
|
| 67 |
+
Configuration for the Intra-Class Block modules, if any, used for enhancing feature representation.
|
| 68 |
+
scale_factor (`int`, *optional*, defaults to 2):
|
| 69 |
+
The scaling factor used for spatial resolution adjustments in the feature maps.
|
| 70 |
+
scale_factor_list (`list[int]`, *optional*, defaults to `None`):
|
| 71 |
+
A list of scaling factors used for spatial resolution adjustments in the feature maps.
|
| 72 |
+
kernel_list (`list[int]`, *optional*, defaults to `[3, 2, 2]`):
|
| 73 |
+
The list of kernel sizes for convolutional layers in the head network for multi-scale feature extraction.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
sub_configs = {"backbone_config": AutoConfig}
|
| 77 |
+
model_type = "pp_ocrv5_server_det"
|
| 78 |
+
|
| 79 |
+
interpolate_mode: str = "nearest"
|
| 80 |
+
backbone_config: dict | PreTrainedConfig | None = None
|
| 81 |
+
neck_out_channels: int = 256
|
| 82 |
+
reduce_factor: int = 2
|
| 83 |
+
intraclass_block_number: int = 4
|
| 84 |
+
intraclass_block_config: dict | None = None
|
| 85 |
+
scale_factor: int = 2
|
| 86 |
+
scale_factor_list: list | None = None
|
| 87 |
+
hidden_act: str = "relu"
|
| 88 |
+
kernel_list: list | None = None
|
| 89 |
+
id2label: dict[int, str] | dict[str, str] | None = None
|
| 90 |
+
|
| 91 |
+
def __post_init__(self, **kwargs):
|
| 92 |
+
self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
|
| 93 |
+
backbone_config=self.backbone_config,
|
| 94 |
+
default_config_type="hgnet_v2",
|
| 95 |
+
default_config_kwargs={
|
| 96 |
+
"arch": "L",
|
| 97 |
+
"return_idx": [0, 1, 2, 3],
|
| 98 |
+
"freeze_stem_only": True,
|
| 99 |
+
"freeze_at": 0,
|
| 100 |
+
"freeze_norm": True,
|
| 101 |
+
"lr_mult_list": [0, 0.05, 0.05, 0.05, 0.05],
|
| 102 |
+
"out_features": ["stage1", "stage2", "stage3", "stage4"],
|
| 103 |
+
},
|
| 104 |
+
**kwargs,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# For object detection pipeline compatibility: single class "text"
|
| 108 |
+
self.id2label = {0: "text"} if self.id2label is None else self.id2label
|
| 109 |
+
super().__post_init__(**kwargs)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class PPOCRV5ServerDetImageProcessorKwargs(ImagesKwargs, total=False):
|
| 113 |
+
r"""
|
| 114 |
+
limit_side_len (`int`, *optional*, defaults to `960`):
|
| 115 |
+
Maximum or minimum side length.
|
| 116 |
+
limit_type (`str`, *optional*, defaults to `max`):
|
| 117 |
+
Resizing strategy: "max", "min", or "resize_long".
|
| 118 |
+
max_side_limit (`int`, *optional* defaults to `4000`):
|
| 119 |
+
Maximum allowed side length.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
limit_side_len: int
|
| 123 |
+
limit_type: str
|
| 124 |
+
max_side_limit: int
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@auto_docstring
|
| 128 |
+
@requires(backends=("torch",))
|
| 129 |
+
class PPOCRV5ServerDetImageProcessor(TorchvisionBackend):
|
| 130 |
+
resample = 2
|
| 131 |
+
image_mean = [0.406, 0.456, 0.485]
|
| 132 |
+
image_std = [0.225, 0.224, 0.229]
|
| 133 |
+
size = {"height": 960, "width": 960}
|
| 134 |
+
do_resize = True
|
| 135 |
+
do_rescale = True
|
| 136 |
+
do_normalize = True
|
| 137 |
+
limit_side_len = 960
|
| 138 |
+
limit_type = "max"
|
| 139 |
+
max_side_limit = 4000
|
| 140 |
+
valid_kwargs = PPOCRV5ServerDetImageProcessorKwargs
|
| 141 |
+
|
| 142 |
+
def _preprocess(
|
| 143 |
+
self,
|
| 144 |
+
images: list["torch.Tensor"],
|
| 145 |
+
do_resize: bool,
|
| 146 |
+
size: SizeDict,
|
| 147 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 148 |
+
do_rescale: bool,
|
| 149 |
+
rescale_factor: float,
|
| 150 |
+
do_normalize: bool,
|
| 151 |
+
image_mean: float | list[float] | None,
|
| 152 |
+
image_std: float | list[float] | None,
|
| 153 |
+
limit_side_len: int,
|
| 154 |
+
limit_type: str,
|
| 155 |
+
max_side_limit: int,
|
| 156 |
+
disable_grouping: bool | None,
|
| 157 |
+
return_tensors: str | TensorType | None,
|
| 158 |
+
**kwargs,
|
| 159 |
+
) -> BatchFeature:
|
| 160 |
+
target_sizes = []
|
| 161 |
+
|
| 162 |
+
# Group images by their original spatial shape to enable batched resizing (optimization for efficiency)
|
| 163 |
+
# [Key Change] Unlike the original implementation, we now track target shapes for each original shape group
|
| 164 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 165 |
+
# Store resized image batches mapped to their original shape keys
|
| 166 |
+
resized_images_grouped = {}
|
| 167 |
+
# [Key Change] Core addition: Mapping from original image shape to target resize shape
|
| 168 |
+
# This dict ensures consistent target shape handling across all subsequent operations (resize/processing)
|
| 169 |
+
target_shape_per_shape = {}
|
| 170 |
+
for shape, stacked_images in grouped_images.items():
|
| 171 |
+
if do_resize:
|
| 172 |
+
resize_size, target_shape = self.get_image_size(
|
| 173 |
+
stacked_images[0], limit_side_len, limit_type, max_side_limit
|
| 174 |
+
)
|
| 175 |
+
target_shape_per_shape[shape] = target_shape
|
| 176 |
+
stacked_images = self.resize(image=stacked_images.float(), size=resize_size, resample=resample)
|
| 177 |
+
resized_images_grouped[shape] = stacked_images
|
| 178 |
+
|
| 179 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 180 |
+
if do_resize:
|
| 181 |
+
target_sizes = [target_shape_per_shape[grouped_images_index[i][0]] for i in range(len(images))]
|
| 182 |
+
|
| 183 |
+
# Group images by size for further processing
|
| 184 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 185 |
+
processed_images_grouped = {}
|
| 186 |
+
for shape, stacked_images in grouped_images.items():
|
| 187 |
+
stacked_images = self.rescale_and_normalize(
|
| 188 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 189 |
+
)
|
| 190 |
+
# BGR to RGB conversion
|
| 191 |
+
stacked_images = stacked_images[:, [2, 1, 0], :, :]
|
| 192 |
+
processed_images_grouped[shape] = stacked_images
|
| 193 |
+
|
| 194 |
+
pixel_values = reorder_images(processed_images_grouped, grouped_images_index)
|
| 195 |
+
|
| 196 |
+
return BatchFeature(
|
| 197 |
+
data={"pixel_values": pixel_values, "target_sizes": target_sizes},
|
| 198 |
+
tensor_type=return_tensors,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def _unclip(self, contour_box, unclip_ratio):
|
| 202 |
+
"""
|
| 203 |
+
Expands (dilates) a detected text bounding box to recover the full text region.
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
contour_box (np.ndarray): Input contour of shape (N, 2), where N is the number of points.
|
| 207 |
+
unclip_ratio (float): Expansion ratio, typically greater than 1.0.
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
np.ndarray: Expanded contour of shape (M, 2).
|
| 211 |
+
"""
|
| 212 |
+
# --- 1. Parameter calculation ---
|
| 213 |
+
polygon = contour_box.reshape(-1, 2).astype(np.float32)
|
| 214 |
+
perimeter = cv2.arcLength(polygon, True)
|
| 215 |
+
area = cv2.contourArea(polygon)
|
| 216 |
+
offset_distance = area * unclip_ratio / perimeter
|
| 217 |
+
|
| 218 |
+
# --- 2. Determine polygon orientation and edge normals ---
|
| 219 |
+
x, y = polygon[:, 0], polygon[:, 1]
|
| 220 |
+
is_counter_clockwise = (x @ np.roll(y, -1) - y @ np.roll(x, -1)) > 0.0
|
| 221 |
+
|
| 222 |
+
edges = np.roll(polygon, -1, axis=0) - polygon
|
| 223 |
+
edge_lengths = np.linalg.norm(edges, axis=1, keepdims=True)
|
| 224 |
+
edge_directions = edges / np.maximum(edge_lengths, 1e-6)
|
| 225 |
+
|
| 226 |
+
if is_counter_clockwise:
|
| 227 |
+
normals = np.stack([edge_directions[:, 1], -edge_directions[:, 0]], axis=1)
|
| 228 |
+
else:
|
| 229 |
+
normals = np.stack([-edge_directions[:, 1], edge_directions[:, 0]], axis=1)
|
| 230 |
+
|
| 231 |
+
# --- 3. Calculate new vertices from intersecting shifted edge lines ---
|
| 232 |
+
shifted_points = polygon + offset_distance * normals
|
| 233 |
+
|
| 234 |
+
prev_shifted_points = np.roll(shifted_points, 1, axis=0)
|
| 235 |
+
prev_edge_directions = np.roll(edge_directions, 1, axis=0)
|
| 236 |
+
|
| 237 |
+
cross_product = (
|
| 238 |
+
prev_edge_directions[:, 0] * edge_directions[:, 1] - prev_edge_directions[:, 1] * edge_directions[:, 0]
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
is_parallel_mask = np.abs(cross_product) < 1e-6
|
| 242 |
+
cross_product_safe = np.where(is_parallel_mask, 1.0, cross_product)
|
| 243 |
+
|
| 244 |
+
vec_to_current = shifted_points - prev_shifted_points
|
| 245 |
+
intersection_param = (
|
| 246 |
+
vec_to_current[:, 0] * edge_directions[:, 1] - vec_to_current[:, 1] * edge_directions[:, 0]
|
| 247 |
+
) / cross_product_safe
|
| 248 |
+
|
| 249 |
+
new_vertices = prev_shifted_points + prev_edge_directions * intersection_param[:, None]
|
| 250 |
+
|
| 251 |
+
# --- 4. Handle near-parallel adjacent edges with a fallback ---
|
| 252 |
+
if np.any(is_parallel_mask):
|
| 253 |
+
prev_normals = np.roll(normals, 1, axis=0)
|
| 254 |
+
fallback_points = polygon + 0.5 * offset_distance * (prev_normals + normals)
|
| 255 |
+
new_vertices[is_parallel_mask] = fallback_points[is_parallel_mask]
|
| 256 |
+
|
| 257 |
+
return np.array([new_vertices.astype(np.float32)])
|
| 258 |
+
|
| 259 |
+
def _get_mini_boxes(self, contour):
|
| 260 |
+
"""
|
| 261 |
+
Computes the minimum-area bounding rectangle for a given contour and returns
|
| 262 |
+
its four corners in a consistent order (top-left, bottom-left, bottom-right, top-right).
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
contour (np.ndarray): Input contour of shape (N, 1, 2).
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
tuple:
|
| 269 |
+
- box (list): List of four corner points in order.
|
| 270 |
+
- short_side_length (float): Length of the shorter side of the bounding rectangle.
|
| 271 |
+
"""
|
| 272 |
+
bounding_box = cv2.minAreaRect(contour)
|
| 273 |
+
points = sorted(cv2.boxPoints(bounding_box), key=lambda x: x[0])
|
| 274 |
+
|
| 275 |
+
index_1, index_2, index_3, index_4 = 0, 1, 2, 3
|
| 276 |
+
if points[1][1] > points[0][1]:
|
| 277 |
+
index_1 = 0
|
| 278 |
+
index_4 = 1
|
| 279 |
+
else:
|
| 280 |
+
index_1 = 1
|
| 281 |
+
index_4 = 0
|
| 282 |
+
if points[3][1] > points[2][1]:
|
| 283 |
+
index_2 = 2
|
| 284 |
+
index_3 = 3
|
| 285 |
+
else:
|
| 286 |
+
index_2 = 3
|
| 287 |
+
index_3 = 2
|
| 288 |
+
|
| 289 |
+
box = [points[index_1], points[index_2], points[index_3], points[index_4]]
|
| 290 |
+
return box, min(bounding_box[1])
|
| 291 |
+
|
| 292 |
+
def _get_box_score(self, bitmap: np.ndarray, polygon_bounding_box: np.ndarray):
|
| 293 |
+
"""
|
| 294 |
+
Computes the mean score of a bounding box region in the prediction map using
|
| 295 |
+
a fast approach with axis-aligned bounding boxes.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
bitmap (np.ndarray): Binary or float prediction map of shape (H, W).
|
| 299 |
+
polygon_bounding_box (np.ndarray): Bounding box polygon of shape (N, 2).
|
| 300 |
+
|
| 301 |
+
Returns:
|
| 302 |
+
float: Mean score within the bounding box region.
|
| 303 |
+
"""
|
| 304 |
+
height, width = bitmap.shape[:2]
|
| 305 |
+
box = polygon_bounding_box.copy()
|
| 306 |
+
xmin = max(0, min(math.floor(box[:, 0].min()), width - 1))
|
| 307 |
+
xmax = max(0, min(math.ceil(box[:, 0].max()), width - 1))
|
| 308 |
+
ymin = max(0, min(math.floor(box[:, 1].min()), height - 1))
|
| 309 |
+
ymax = max(0, min(math.ceil(box[:, 1].max()), height - 1))
|
| 310 |
+
|
| 311 |
+
mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
|
| 312 |
+
box[:, 0] = box[:, 0] - xmin
|
| 313 |
+
box[:, 1] = box[:, 1] - ymin
|
| 314 |
+
cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
|
| 315 |
+
return cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0]
|
| 316 |
+
|
| 317 |
+
def _boxes_from_bitmap(
|
| 318 |
+
self,
|
| 319 |
+
prediction: np.ndarray,
|
| 320 |
+
bitmap: np.ndarray,
|
| 321 |
+
dest_width: int,
|
| 322 |
+
dest_height: int,
|
| 323 |
+
box_threshold: float,
|
| 324 |
+
unclip_ratio: float,
|
| 325 |
+
min_size: int,
|
| 326 |
+
max_candidates: int,
|
| 327 |
+
):
|
| 328 |
+
"""
|
| 329 |
+
Extracts axis-aligned or rotated bounding boxes from a binary segmentation map.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
prediction (np.ndarray): Raw prediction map of shape (H, W).
|
| 333 |
+
bitmap (np.ndarray): Binarized segmentation map of shape (H, W).
|
| 334 |
+
dest_width (int): Original image width for scaling back.
|
| 335 |
+
dest_height (int): Original image height for scaling back.
|
| 336 |
+
box_threshold (float): Score threshold for filtering low-confidence boxes.
|
| 337 |
+
unclip_ratio (float): Expansion ratio for contour unclipping.
|
| 338 |
+
min_size (int): Minimum side length of valid boxes.
|
| 339 |
+
max_candidates (int): Maximum number of contours to process.
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
tuple:
|
| 343 |
+
- boxes (np.ndarray): Array of boxes, each of shape (4, 2).
|
| 344 |
+
- scores (list): List of corresponding scores.
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
height, width = bitmap.shape
|
| 348 |
+
width_scale = dest_width / width
|
| 349 |
+
height_scale = dest_height / height
|
| 350 |
+
|
| 351 |
+
outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
| 352 |
+
|
| 353 |
+
contours = outs[1] if len(outs) == 3 else outs[0]
|
| 354 |
+
|
| 355 |
+
num_contours = min(len(contours), max_candidates)
|
| 356 |
+
|
| 357 |
+
boxes = []
|
| 358 |
+
scores = []
|
| 359 |
+
for index in range(num_contours):
|
| 360 |
+
contour = contours[index]
|
| 361 |
+
points, short_side_length = self._get_mini_boxes(contour)
|
| 362 |
+
if short_side_length < min_size:
|
| 363 |
+
continue
|
| 364 |
+
points = np.array(points)
|
| 365 |
+
score = self._get_box_score(prediction, points.reshape(-1, 2))
|
| 366 |
+
if box_threshold > score:
|
| 367 |
+
continue
|
| 368 |
+
box = self._unclip(points, unclip_ratio).reshape(-1, 1, 2)
|
| 369 |
+
box, short_side_length = self._get_mini_boxes(box)
|
| 370 |
+
if short_side_length < min_size + 2:
|
| 371 |
+
continue
|
| 372 |
+
|
| 373 |
+
box = np.array(box)
|
| 374 |
+
for i in range(box.shape[0]):
|
| 375 |
+
box[i, 0] = max(0, min(round(box[i, 0] * width_scale), dest_width))
|
| 376 |
+
box[i, 1] = max(0, min(round(box[i, 1] * height_scale), dest_height))
|
| 377 |
+
|
| 378 |
+
boxes.append(box.astype(np.int16))
|
| 379 |
+
scores.append(score)
|
| 380 |
+
return np.array(boxes, dtype=np.int16), scores
|
| 381 |
+
|
| 382 |
+
def get_image_size(
|
| 383 |
+
self,
|
| 384 |
+
image: "torch.Tensor",
|
| 385 |
+
limit_side_len: int,
|
| 386 |
+
limit_type: str,
|
| 387 |
+
max_side_limit: int,
|
| 388 |
+
):
|
| 389 |
+
"""
|
| 390 |
+
Computes the target size for resizing an image while preserving aspect ratio.
|
| 391 |
+
|
| 392 |
+
Args:
|
| 393 |
+
image (torch.Tensor): Input image.
|
| 394 |
+
limit_side_len (int): Maximum or minimum side length.
|
| 395 |
+
limit_type (str): Resizing strategy: "max", "min", or "resize_long".
|
| 396 |
+
max_side_limit (int): Maximum allowed side length.
|
| 397 |
+
|
| 398 |
+
Returns:
|
| 399 |
+
tuple:
|
| 400 |
+
- SizeDict: Target size.
|
| 401 |
+
- torch.Tensor: Original size.
|
| 402 |
+
"""
|
| 403 |
+
_, height, width = image.shape
|
| 404 |
+
height, width = int(height), int(width)
|
| 405 |
+
|
| 406 |
+
if limit_type == "max":
|
| 407 |
+
if max(height, width) > limit_side_len:
|
| 408 |
+
ratio = float(limit_side_len) / max(height, width)
|
| 409 |
+
else:
|
| 410 |
+
ratio = 1.0
|
| 411 |
+
elif limit_type == "min":
|
| 412 |
+
if min(height, width) < limit_side_len:
|
| 413 |
+
ratio = float(limit_side_len) / min(height, width)
|
| 414 |
+
else:
|
| 415 |
+
ratio = 1.0
|
| 416 |
+
elif limit_type == "resize_long":
|
| 417 |
+
ratio = float(limit_side_len) / max(height, width)
|
| 418 |
+
else:
|
| 419 |
+
raise ValueError(f"PPOCRV5ServerDetImageProcessor does not support limit type: {limit_type}")
|
| 420 |
+
|
| 421 |
+
resize_height = int(height * ratio)
|
| 422 |
+
resize_width = int(width * ratio)
|
| 423 |
+
|
| 424 |
+
if max_side_limit is not None and max(resize_height, resize_width) > max_side_limit:
|
| 425 |
+
ratio = float(max_side_limit) / max(resize_height, resize_width)
|
| 426 |
+
resize_height = int(resize_height * ratio)
|
| 427 |
+
resize_width = int(resize_width * ratio)
|
| 428 |
+
|
| 429 |
+
resize_height = max(int(round(resize_height / 32) * 32), 32)
|
| 430 |
+
resize_width = max(int(round(resize_width / 32) * 32), 32)
|
| 431 |
+
|
| 432 |
+
return SizeDict(height=resize_height, width=resize_width), torch.tensor(
|
| 433 |
+
[height, width], dtype=torch.float32, device=image.device
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
def post_process_object_detection(
|
| 437 |
+
self,
|
| 438 |
+
predictions,
|
| 439 |
+
threshold: float = 0.3,
|
| 440 |
+
target_sizes: list[tuple[int, int]] | TensorType | None = None,
|
| 441 |
+
box_threshold: float = 0.6,
|
| 442 |
+
max_candidates: int = 1000,
|
| 443 |
+
min_size: int = 3,
|
| 444 |
+
unclip_ratio: float = 1.5,
|
| 445 |
+
):
|
| 446 |
+
"""
|
| 447 |
+
Converts model outputs into detected text boxes in corners format (xmin, ymin, xmax, ymax).
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
predictions: Model outputs with `logits` attribute (probability maps of shape `(batch_size, 1, H, W)`).
|
| 451 |
+
threshold (float): Binarization threshold.
|
| 452 |
+
target_sizes: Original image sizes (height, width) per image.
|
| 453 |
+
box_threshold (float): Box score threshold.
|
| 454 |
+
max_candidates (int): Maximum number of boxes.
|
| 455 |
+
min_size (int): Minimum box size.
|
| 456 |
+
unclip_ratio (float): Expansion ratio.
|
| 457 |
+
|
| 458 |
+
Returns:
|
| 459 |
+
list[dict]: List of detection results per image. Each dict contains:
|
| 460 |
+
- "boxes": `torch.Tensor` of shape `(N, 4)` in corners format (xmin, ymin, xmax, ymax)
|
| 461 |
+
- "scores": `torch.Tensor` of shape `(N,)`
|
| 462 |
+
- "labels": `torch.Tensor` of shape `(N,)` (class id 0 for text)
|
| 463 |
+
"""
|
| 464 |
+
requires_backends(self, ["torch", "cv2"])
|
| 465 |
+
if target_sizes is None:
|
| 466 |
+
raise ValueError("target_sizes must be provided for post_process_object_detection")
|
| 467 |
+
|
| 468 |
+
device = predictions.last_hidden_state.device
|
| 469 |
+
results = []
|
| 470 |
+
for prediction, size in zip(predictions.last_hidden_state, target_sizes):
|
| 471 |
+
prediction = prediction[0, :, :].cpu().detach().numpy()
|
| 472 |
+
size = size.cpu().detach().numpy()
|
| 473 |
+
src_height, src_width = size
|
| 474 |
+
mask = prediction > threshold
|
| 475 |
+
boxes, scores = self._boxes_from_bitmap(
|
| 476 |
+
prediction, mask, src_width, src_height, box_threshold, unclip_ratio, min_size, max_candidates
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
results.append(
|
| 480 |
+
{
|
| 481 |
+
"boxes": torch.from_numpy(boxes).to(device),
|
| 482 |
+
"scores": torch.tensor(scores, dtype=torch.float32, device=device),
|
| 483 |
+
"labels": torch.zeros(len(scores), dtype=torch.long, device=device), # Single class: text
|
| 484 |
+
}
|
| 485 |
+
)
|
| 486 |
+
return results
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
class PPOCRV5ServerDetIntraclassBlock(nn.Module):
|
| 490 |
+
"""
|
| 491 |
+
Intra-Class Relationship Block. It uses multi-scale convolution (7x7, 5x5, 3x3)
|
| 492 |
+
and asymmetric kernels (e.g., 7x1, 1x7) to capture long-range spatial dependencies
|
| 493 |
+
within text regions.
|
| 494 |
+
"""
|
| 495 |
+
|
| 496 |
+
def __init__(
|
| 497 |
+
self,
|
| 498 |
+
intraclass_block_config: dict | None = None,
|
| 499 |
+
in_channels: int = 96,
|
| 500 |
+
reduce_factor: int = 4,
|
| 501 |
+
):
|
| 502 |
+
super().__init__()
|
| 503 |
+
|
| 504 |
+
reduced_channels = in_channels // reduce_factor
|
| 505 |
+
|
| 506 |
+
self.conv_reduce_channel = nn.Conv2d(in_channels, reduced_channels, *intraclass_block_config["reduce_channel"])
|
| 507 |
+
|
| 508 |
+
self.vertical_long_to_small_conv_longratio = nn.Conv2d(
|
| 509 |
+
reduced_channels, reduced_channels, *intraclass_block_config["vertical_long_to_small_conv_longratio"]
|
| 510 |
+
)
|
| 511 |
+
self.vertical_long_to_small_conv_midratio = nn.Conv2d(
|
| 512 |
+
reduced_channels, reduced_channels, *intraclass_block_config["vertical_long_to_small_conv_midratio"]
|
| 513 |
+
)
|
| 514 |
+
self.vertical_long_to_small_conv_shortratio = nn.Conv2d(
|
| 515 |
+
reduced_channels, reduced_channels, *intraclass_block_config["vertical_long_to_small_conv_shortratio"]
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
self.horizontal_small_to_long_conv_longratio = nn.Conv2d(
|
| 519 |
+
reduced_channels, reduced_channels, *intraclass_block_config["horizontal_small_to_long_conv_longratio"]
|
| 520 |
+
)
|
| 521 |
+
self.horizontal_small_to_long_conv_midratio = nn.Conv2d(
|
| 522 |
+
reduced_channels, reduced_channels, *intraclass_block_config["horizontal_small_to_long_conv_midratio"]
|
| 523 |
+
)
|
| 524 |
+
self.horizontal_small_to_long_conv_shortratio = nn.Conv2d(
|
| 525 |
+
reduced_channels, reduced_channels, *intraclass_block_config["horizontal_small_to_long_conv_shortratio"]
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
self.symmetric_conv_long_longratio = nn.Conv2d(
|
| 529 |
+
reduced_channels, reduced_channels, *intraclass_block_config["symmetric_conv_long_longratio"]
|
| 530 |
+
)
|
| 531 |
+
self.symmetric_conv_long_midratio = nn.Conv2d(
|
| 532 |
+
reduced_channels, reduced_channels, *intraclass_block_config["symmetric_conv_long_midratio"]
|
| 533 |
+
)
|
| 534 |
+
self.symmetric_conv_long_shortratio = nn.Conv2d(
|
| 535 |
+
reduced_channels, reduced_channels, *intraclass_block_config["symmetric_conv_long_shortratio"]
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
self.conv_final = PPOCRV5ServerDetConvBatchnormLayer(
|
| 539 |
+
in_channels=reduced_channels,
|
| 540 |
+
out_channels=in_channels,
|
| 541 |
+
kernel_size=intraclass_block_config["return_channel"][0],
|
| 542 |
+
stride=intraclass_block_config["return_channel"][1],
|
| 543 |
+
padding=intraclass_block_config["return_channel"][2],
|
| 544 |
+
bias=True,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 548 |
+
residual = hidden_states
|
| 549 |
+
hidden_states = self.conv_reduce_channel(hidden_states)
|
| 550 |
+
|
| 551 |
+
hidden_states = (
|
| 552 |
+
self.symmetric_conv_long_longratio(hidden_states)
|
| 553 |
+
+ self.vertical_long_to_small_conv_longratio(hidden_states)
|
| 554 |
+
+ self.horizontal_small_to_long_conv_longratio(hidden_states)
|
| 555 |
+
)
|
| 556 |
+
hidden_states = (
|
| 557 |
+
self.symmetric_conv_long_midratio(hidden_states)
|
| 558 |
+
+ self.vertical_long_to_small_conv_midratio(hidden_states)
|
| 559 |
+
+ self.horizontal_small_to_long_conv_midratio(hidden_states)
|
| 560 |
+
)
|
| 561 |
+
hidden_states = (
|
| 562 |
+
self.symmetric_conv_long_shortratio(hidden_states)
|
| 563 |
+
+ self.vertical_long_to_small_conv_shortratio(hidden_states)
|
| 564 |
+
+ self.horizontal_small_to_long_conv_shortratio(hidden_states)
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
hidden_states = self.conv_final(hidden_states)
|
| 568 |
+
|
| 569 |
+
return residual + hidden_states
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class PPOCRV5ServerDetNeck(nn.Module):
|
| 573 |
+
"""
|
| 574 |
+
Large Kernel Path Aggregation Network (Neck) for PPOCRV5 Server Detection.
|
| 575 |
+
Fuses multi-scale features from backbone stages (stage 2 to stage 5) via top-down and bottom-up paths,
|
| 576 |
+
enhanced with large kernel convolution for better spatial dependency modeling.
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
def __init__(self, config):
|
| 580 |
+
super().__init__()
|
| 581 |
+
self.interpolate_mode = config.interpolate_mode
|
| 582 |
+
self.scale_factor_list = config.scale_factor_list
|
| 583 |
+
self.num_backbone_stages = len(config.backbone_config.stage_out_channels)
|
| 584 |
+
|
| 585 |
+
self.input_channel_adjustment_convolution = nn.ModuleList()
|
| 586 |
+
self.input_feature_projection_convolution = nn.ModuleList()
|
| 587 |
+
self.path_aggregation_head_convolution = nn.ModuleList()
|
| 588 |
+
self.path_aggregation_lateral_convolution = nn.ModuleList()
|
| 589 |
+
|
| 590 |
+
backbone_stage_output_channels = config.backbone_config.stage_out_channels
|
| 591 |
+
|
| 592 |
+
for backbone_stage_index in range(len(backbone_stage_output_channels)):
|
| 593 |
+
channel_adjustment_convolution = nn.Conv2d(
|
| 594 |
+
in_channels=backbone_stage_output_channels[backbone_stage_index],
|
| 595 |
+
out_channels=config.neck_out_channels,
|
| 596 |
+
kernel_size=1,
|
| 597 |
+
bias=False,
|
| 598 |
+
)
|
| 599 |
+
self.input_channel_adjustment_convolution.append(channel_adjustment_convolution)
|
| 600 |
+
|
| 601 |
+
feature_projection_convolution = nn.Conv2d(
|
| 602 |
+
in_channels=config.neck_out_channels,
|
| 603 |
+
out_channels=config.neck_out_channels // 4,
|
| 604 |
+
kernel_size=9,
|
| 605 |
+
padding=4,
|
| 606 |
+
bias=False,
|
| 607 |
+
)
|
| 608 |
+
self.input_feature_projection_convolution.append(feature_projection_convolution)
|
| 609 |
+
|
| 610 |
+
if backbone_stage_index > 0:
|
| 611 |
+
pan_head_convolution = nn.Conv2d(
|
| 612 |
+
in_channels=config.neck_out_channels // 4,
|
| 613 |
+
out_channels=config.neck_out_channels // 4,
|
| 614 |
+
kernel_size=3,
|
| 615 |
+
padding=1,
|
| 616 |
+
stride=2,
|
| 617 |
+
bias=False,
|
| 618 |
+
)
|
| 619 |
+
self.path_aggregation_head_convolution.append(pan_head_convolution)
|
| 620 |
+
|
| 621 |
+
pan_lateral_convolution = nn.Conv2d(
|
| 622 |
+
in_channels=config.neck_out_channels // 4,
|
| 623 |
+
out_channels=config.neck_out_channels // 4,
|
| 624 |
+
kernel_size=9,
|
| 625 |
+
padding=4,
|
| 626 |
+
bias=False,
|
| 627 |
+
)
|
| 628 |
+
self.path_aggregation_lateral_convolution.append(pan_lateral_convolution)
|
| 629 |
+
|
| 630 |
+
self.intraclass_blocks = nn.ModuleList()
|
| 631 |
+
for _ in range(config.intraclass_block_number):
|
| 632 |
+
self.intraclass_blocks.append(
|
| 633 |
+
PPOCRV5ServerDetIntraclassBlock(
|
| 634 |
+
config.intraclass_block_config, config.neck_out_channels // 4, reduce_factor=config.reduce_factor
|
| 635 |
+
)
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
def forward(self, backbone_stage_feature_maps: list[torch.Tensor], **kwargs) -> torch.Tensor:
|
| 639 |
+
channel_adjusted = []
|
| 640 |
+
for i, feature_map in enumerate(backbone_stage_feature_maps):
|
| 641 |
+
hidden_states = self.input_channel_adjustment_convolution[i](feature_map)
|
| 642 |
+
channel_adjusted.append(hidden_states)
|
| 643 |
+
|
| 644 |
+
top_down = [None] * self.num_backbone_stages
|
| 645 |
+
top_down[3] = channel_adjusted[3]
|
| 646 |
+
for i in range(self.num_backbone_stages - 2, -1, -1):
|
| 647 |
+
top_down[i] = channel_adjusted[i] + F.interpolate(
|
| 648 |
+
top_down[i + 1], scale_factor=2, mode=self.interpolate_mode
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
projected = []
|
| 652 |
+
for i in range(self.num_backbone_stages):
|
| 653 |
+
hidden_states = top_down[i] if i < self.num_backbone_stages - 1 else channel_adjusted[-1]
|
| 654 |
+
hidden_states = self.input_feature_projection_convolution[i](hidden_states)
|
| 655 |
+
projected.append(hidden_states)
|
| 656 |
+
|
| 657 |
+
bottom_up = [None] * self.num_backbone_stages
|
| 658 |
+
bottom_up[0] = projected[0]
|
| 659 |
+
for i in range(1, self.num_backbone_stages):
|
| 660 |
+
bottom_up[i] = projected[i] + self.path_aggregation_head_convolution[i - 1](bottom_up[i - 1])
|
| 661 |
+
|
| 662 |
+
lateral_refined = []
|
| 663 |
+
for i in range(self.num_backbone_stages):
|
| 664 |
+
hidden_states = projected[0] if i == 0 else bottom_up[i]
|
| 665 |
+
hidden_states = self.path_aggregation_lateral_convolution[i](hidden_states)
|
| 666 |
+
lateral_refined.append(hidden_states)
|
| 667 |
+
|
| 668 |
+
intraclass_refined = [block(feature) for block, feature in zip(self.intraclass_blocks, lateral_refined)]
|
| 669 |
+
|
| 670 |
+
upsampled = []
|
| 671 |
+
for feature, scale_factor in zip(intraclass_refined, self.scale_factor_list):
|
| 672 |
+
if scale_factor > 1:
|
| 673 |
+
hidden_states = F.interpolate(feature, scale_factor=scale_factor, mode=self.interpolate_mode)
|
| 674 |
+
else:
|
| 675 |
+
hidden_states = feature
|
| 676 |
+
upsampled.append(hidden_states)
|
| 677 |
+
|
| 678 |
+
upsampled = [
|
| 679 |
+
F.interpolate(feature, scale_factor=scale_factor, mode=self.interpolate_mode)
|
| 680 |
+
if scale_factor > 1
|
| 681 |
+
else feature
|
| 682 |
+
for feature, scale_factor in zip(intraclass_refined, self.scale_factor_list)
|
| 683 |
+
]
|
| 684 |
+
|
| 685 |
+
return torch.cat(upsampled[::-1], dim=1)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
class PPOCRV5ServerDetConvBatchnormLayer(nn.Module):
|
| 689 |
+
"""
|
| 690 |
+
A basic wrapper for Convolution-BatchNorm-Activation, typically used for head components.
|
| 691 |
+
"""
|
| 692 |
+
|
| 693 |
+
def __init__(
|
| 694 |
+
self,
|
| 695 |
+
in_channels: int,
|
| 696 |
+
out_channels: int,
|
| 697 |
+
kernel_size: int,
|
| 698 |
+
stride: int = 1,
|
| 699 |
+
padding: int | str = 1,
|
| 700 |
+
groups: int = 1,
|
| 701 |
+
activation: str = "relu",
|
| 702 |
+
bias: bool = False,
|
| 703 |
+
convolution_transpose: bool = False,
|
| 704 |
+
):
|
| 705 |
+
super().__init__()
|
| 706 |
+
if convolution_transpose:
|
| 707 |
+
self.convolution = nn.ConvTranspose2d(
|
| 708 |
+
in_channels=in_channels,
|
| 709 |
+
out_channels=out_channels,
|
| 710 |
+
kernel_size=kernel_size,
|
| 711 |
+
stride=stride,
|
| 712 |
+
)
|
| 713 |
+
else:
|
| 714 |
+
self.convolution = nn.Conv2d(
|
| 715 |
+
in_channels=in_channels,
|
| 716 |
+
out_channels=out_channels,
|
| 717 |
+
kernel_size=kernel_size,
|
| 718 |
+
stride=stride,
|
| 719 |
+
padding=padding,
|
| 720 |
+
groups=groups,
|
| 721 |
+
bias=bias,
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
self.norm = nn.BatchNorm2d(out_channels)
|
| 725 |
+
self.act_fn = nn.Identity() if activation is None else ACT2FN[activation]
|
| 726 |
+
|
| 727 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 728 |
+
hidden_states = self.convolution(hidden_states)
|
| 729 |
+
hidden_states = self.norm(hidden_states)
|
| 730 |
+
hidden_states = self.act_fn(hidden_states)
|
| 731 |
+
return hidden_states
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
class PPOCRV5ServerDetSegmentationHead(nn.Module):
|
| 735 |
+
"""
|
| 736 |
+
Standard segmentation head for generating probability maps. It uses transposed
|
| 737 |
+
convolution to upsample the feature map back to the original image size.
|
| 738 |
+
"""
|
| 739 |
+
|
| 740 |
+
def __init__(
|
| 741 |
+
self,
|
| 742 |
+
config: PPOCRV5ServerDetConfig,
|
| 743 |
+
):
|
| 744 |
+
super().__init__()
|
| 745 |
+
|
| 746 |
+
in_channels = config.neck_out_channels
|
| 747 |
+
kernel_list = config.kernel_list
|
| 748 |
+
self.conv_down = PPOCRV5ServerDetConvBatchnormLayer(
|
| 749 |
+
in_channels=in_channels,
|
| 750 |
+
out_channels=in_channels // 4,
|
| 751 |
+
kernel_size=kernel_list[0],
|
| 752 |
+
padding=int(kernel_list[0] // 2),
|
| 753 |
+
)
|
| 754 |
+
self.conv_up = PPOCRV5ServerDetConvBatchnormLayer(
|
| 755 |
+
in_channels=in_channels // 4,
|
| 756 |
+
out_channels=in_channels // 4,
|
| 757 |
+
kernel_size=kernel_list[1],
|
| 758 |
+
stride=2,
|
| 759 |
+
convolution_transpose=True,
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
self.conv_final = nn.ConvTranspose2d(
|
| 763 |
+
in_channels=in_channels // 4,
|
| 764 |
+
out_channels=1,
|
| 765 |
+
kernel_size=kernel_list[2],
|
| 766 |
+
stride=2,
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 770 |
+
hidden_states = self.conv_down(hidden_states)
|
| 771 |
+
hidden_states = self.conv_up(hidden_states)
|
| 772 |
+
feature = hidden_states
|
| 773 |
+
hidden_states = self.conv_final(hidden_states)
|
| 774 |
+
hidden_states = torch.sigmoid(hidden_states)
|
| 775 |
+
return hidden_states, feature
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
class PPOCRV5ServerDetLocalModule(nn.Module):
|
| 779 |
+
"""
|
| 780 |
+
Local Refinement Module that refines the initial probability map by
|
| 781 |
+
concatenating it with higher-resolution features.
|
| 782 |
+
"""
|
| 783 |
+
|
| 784 |
+
def __init__(self, in_channels: int, out_channels: int, hidden_act: str):
|
| 785 |
+
super().__init__()
|
| 786 |
+
self.convolution_backbone = PPOCRV5ServerDetConvBatchnormLayer(
|
| 787 |
+
in_channels=in_channels + 1,
|
| 788 |
+
out_channels=out_channels,
|
| 789 |
+
kernel_size=3,
|
| 790 |
+
stride=1,
|
| 791 |
+
padding=1,
|
| 792 |
+
activation=hidden_act,
|
| 793 |
+
)
|
| 794 |
+
self.convolution_final = nn.Conv2d(
|
| 795 |
+
in_channels=out_channels,
|
| 796 |
+
out_channels=1,
|
| 797 |
+
kernel_size=1,
|
| 798 |
+
stride=1,
|
| 799 |
+
padding=0,
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
def forward(self, hidden_states: torch.Tensor, init_map: torch.Tensor) -> torch.Tensor:
|
| 803 |
+
hidden_states = torch.cat([init_map, hidden_states], dim=1)
|
| 804 |
+
# last Conv
|
| 805 |
+
hidden_states = self.convolution_backbone(hidden_states)
|
| 806 |
+
hidden_states = self.convolution_final(hidden_states)
|
| 807 |
+
return hidden_states
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
class PPOCRV5ServerDetHead(nn.Module):
|
| 811 |
+
"""
|
| 812 |
+
PPOCRV5ServerDetHead implements the Progressive Fusion Head with Local refinement,
|
| 813 |
+
the core detection head of PP-OCRv5.
|
| 814 |
+
"""
|
| 815 |
+
|
| 816 |
+
def __init__(self, config: PPOCRV5ServerDetConfig):
|
| 817 |
+
super().__init__()
|
| 818 |
+
self.binarize_head = PPOCRV5ServerDetSegmentationHead(config)
|
| 819 |
+
self.upsample_convolution = nn.Upsample(scale_factor=config.scale_factor, mode=config.interpolate_mode)
|
| 820 |
+
|
| 821 |
+
self.local_refinement_module = PPOCRV5ServerDetLocalModule(
|
| 822 |
+
config.neck_out_channels // 4, config.neck_out_channels // 4, config.hidden_act
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 826 |
+
hidden_states, feature = self.binarize_head(hidden_states)
|
| 827 |
+
residual = hidden_states
|
| 828 |
+
feature = self.upsample_convolution(feature)
|
| 829 |
+
hidden_states = self.local_refinement_module(feature, hidden_states)
|
| 830 |
+
hidden_states = torch.sigmoid(hidden_states)
|
| 831 |
+
|
| 832 |
+
return 0.5 * (residual + hidden_states)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
class PPOCRV5ServerDetPreTrainedModel(PreTrainedModel):
|
| 836 |
+
"""
|
| 837 |
+
Base class for all PPOCRV5 Server Det pre-trained models. Handles model initialization,
|
| 838 |
+
configuration, and loading of pre-trained weights, following the Transformers library conventions.
|
| 839 |
+
"""
|
| 840 |
+
|
| 841 |
+
config: PPOCRV5ServerDetConfig
|
| 842 |
+
base_model_prefix = "pp_ocrv5_server_det"
|
| 843 |
+
main_input_name = "pixel_values"
|
| 844 |
+
input_modalities = ("image",)
|
| 845 |
+
_can_compile_fullgraph = True
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
@auto_docstring
|
| 849 |
+
class PPOCRV5ServerDetModel(PPOCRV5ServerDetPreTrainedModel):
|
| 850 |
+
def __init__(self, config: PPOCRV5ServerDetConfig):
|
| 851 |
+
super().__init__(config)
|
| 852 |
+
self.backbone = load_backbone(config)
|
| 853 |
+
self.neck = PPOCRV5ServerDetNeck(config)
|
| 854 |
+
self.post_init()
|
| 855 |
+
|
| 856 |
+
@can_return_tuple
|
| 857 |
+
@auto_docstring
|
| 858 |
+
def forward(
|
| 859 |
+
self,
|
| 860 |
+
pixel_values: torch.FloatTensor,
|
| 861 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 862 |
+
) -> tuple[torch.FloatTensor] | BaseModelOutputWithNoAttention:
|
| 863 |
+
backbone_outputs = self.backbone(pixel_values, **kwargs)
|
| 864 |
+
hidden_state = backbone_outputs.feature_maps
|
| 865 |
+
hidden_state = self.neck(hidden_state)
|
| 866 |
+
|
| 867 |
+
return BaseModelOutputWithNoAttention(
|
| 868 |
+
last_hidden_state=hidden_state,
|
| 869 |
+
hidden_states=backbone_outputs.hidden_states,
|
| 870 |
+
)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
@auto_docstring(
|
| 874 |
+
custom_intro="""
|
| 875 |
+
PPOCRV5 Server Det model for object (text) detection tasks. Wraps the core PPOCRV5ServerDetModel
|
| 876 |
+
and returns outputs compatible with the Transformers object detection API.
|
| 877 |
+
"""
|
| 878 |
+
)
|
| 879 |
+
class PPOCRV5ServerDetForObjectDetection(PPOCRV5ServerDetPreTrainedModel):
|
| 880 |
+
_keys_to_ignore_on_load_missing = ["num_batches_tracked"]
|
| 881 |
+
|
| 882 |
+
def __init__(self, config: PPOCRV5ServerDetConfig):
|
| 883 |
+
super().__init__(config)
|
| 884 |
+
self.model = PPOCRV5ServerDetModel(config)
|
| 885 |
+
self.head = PPOCRV5ServerDetHead(config)
|
| 886 |
+
self.post_init()
|
| 887 |
+
|
| 888 |
+
@can_return_tuple
|
| 889 |
+
def forward(
|
| 890 |
+
self,
|
| 891 |
+
pixel_values: torch.FloatTensor,
|
| 892 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 893 |
+
) -> tuple[torch.FloatTensor] | BaseModelOutputWithNoAttention:
|
| 894 |
+
outputs = self.model(pixel_values, **kwargs)
|
| 895 |
+
logits = self.head(outputs.last_hidden_state)
|
| 896 |
+
|
| 897 |
+
return BaseModelOutputWithNoAttention(
|
| 898 |
+
last_hidden_state=logits,
|
| 899 |
+
hidden_states=outputs.hidden_states,
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
__all__ = [
|
| 904 |
+
"PPOCRV5ServerDetForObjectDetection",
|
| 905 |
+
"PPOCRV5ServerDetImageProcessor",
|
| 906 |
+
"PPOCRV5ServerDetConfig",
|
| 907 |
+
"PPOCRV5ServerDetModel",
|
| 908 |
+
"PPOCRV5ServerDetPreTrainedModel",
|
| 909 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_088000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e08695192e717e5b12f7965b6cdf89da85feff4518dd8f16b30beb30ab4aba47
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_202000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:26ee342cc83a66b0a439ca07076c00fc6bb91fd623f4d934b44d6f9e9a2b9b7a
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_224000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:36a29854988bc999258f51762d1be64735d0a5b81b961493339febaa5dfef356
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_230000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5070a58301b326d912ae9b2b0a8eb77d8d65a830eb949f4d10af2875b32181bb
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_354000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c513f36c07e711ac6b002aaef0a46198e2ac555be163992717326c10e1d9cb94
|
| 3 |
+
size 927700322
|