rick003 commited on
Commit
9a2b78c
·
verified ·
1 Parent(s): 2a2290c

optimize colab training speed and gpu utilization

Browse files
colab/colab_gas_valve_auto_label_train.ipynb CHANGED
@@ -56,7 +56,9 @@
56
  "\n",
57
  "- 阀门标签默认使用 HuggingFace 上的 `reviewed_labels/valve`。\n",
58
  "- 之前失败的整图阀门自动标注模式不会默认参与训练。\n",
59
- "- 训练默认使用 `yolo11x-seg.pt`、120 轮、图片尺寸 640、自动 batch、训练/验证/测试 70/15/15 划分。\n",
 
 
60
  "- 生成的标签和训练结果默认上传回同一个数据集仓库。"
61
  ]
62
  },
@@ -103,6 +105,7 @@
103
  " HfApi,\n",
104
  " login,\n",
105
  " snapshot_download,\n",
 
106
  " CommitOperationAdd,\n",
107
  ")\n",
108
  "\n",
@@ -1066,20 +1069,45 @@
1066
  "\n",
1067
  "training_manifest_rows: list[dict] = []\n",
1068
  "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1069
  "\n",
1070
  "def materialize(split: str, split_samples: list[dict]) -> None:\n",
1071
  " for idx, sample in enumerate(split_samples, 1):\n",
1072
- " suffix = sample[\"image\"].suffix.lower()\n",
1073
  " stem = f\"{sample['source']}_{idx:05d}\"\n",
1074
- " dst_img = COMBINED_DATASET / f\"images/{split}/{stem}{suffix}\"\n",
1075
  " dst_lbl = COMBINED_DATASET / f\"labels/{split}/{stem}.txt\"\n",
1076
- " shutil.copy2(sample[\"image\"], dst_img)\n",
1077
  " write_lines(dst_lbl, sample[\"lines\"])\n",
1078
  " training_manifest_rows.append({\n",
1079
  " \"split\": split,\n",
1080
  " \"dataset_stem\": stem,\n",
1081
  " \"image_path\": str(dst_img),\n",
1082
  " \"label_path\": str(dst_lbl),\n",
 
1083
  " \"source_key\": sample[\"source_key\"],\n",
1084
  " \"source\": sample[\"source\"],\n",
1085
  " \"source_stem\": sample[\"source_stem\"],\n",
@@ -1092,6 +1120,9 @@
1092
  "materialize(\"train\", train_samples)\n",
1093
  "materialize(\"val\", val_samples)\n",
1094
  "materialize(\"test\", test_samples)\n",
 
 
 
1095
  "pd.DataFrame(training_manifest_rows).to_csv(\n",
1096
  " COMBINED_MANIFEST_PATH,\n",
1097
  " index=False,\n",
@@ -1413,24 +1444,73 @@
1413
  "outputs": [],
1414
  "source": [
1415
  "# @title Step 12 - 训练 YOLO-seg\n",
1416
- "# @markdown 训练参数已经按本项目设置好:高精度模型、120 轮、图片尺寸 640、自动 batch。\n",
1417
  "\n",
1418
  "from ultralytics import YOLO\n",
1419
  "\n",
1420
- "TRAIN_MODEL = \"yolo11x-seg.pt\" # 优先保证精度。\n",
1421
- "EPOCHS = 120 # 最多训练 120 轮,早停可能提前结束。\n",
1422
- "IMG_SIZE = 640 # YOLO 分割常用图片尺寸。\n",
1423
- "BATCH = -1 # 让 Ultralytics 自动选择显存能承受的 batch。\n",
1424
- "PATIENCE = 35 # 验证集 35 轮不提升就早停。\n",
 
 
 
 
 
 
1425
  "RUN_NAME = f\"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}\"\n",
1426
  "AUTO_UPLOAD_TRAINING_RESULTS = True\n",
1427
  "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1428
  "print(\"训练参数\")\n",
1429
  "print(f\" model: {TRAIN_MODEL}\")\n",
 
1430
  "print(f\" data: {YAML_PATH}\")\n",
1431
  "print(f\" epochs: {EPOCHS}\")\n",
1432
  "print(f\" imgsz: {IMG_SIZE}\")\n",
1433
  "print(f\" batch: {BATCH}\")\n",
 
 
 
1434
  "print(f\" run: {RUN_NAME}\")\n",
1435
  "\n",
1436
  "\n",
@@ -1493,6 +1573,13 @@
1493
  "\n",
1494
  "\n",
1495
  "model = YOLO(TRAIN_MODEL)\n",
 
 
 
 
 
 
 
1496
  "t_start = time.time()\n",
1497
  "train_results = model.train(\n",
1498
  " data=str(YAML_PATH),\n",
@@ -1503,8 +1590,10 @@
1503
  " project=\"/content/runs\",\n",
1504
  " name=RUN_NAME,\n",
1505
  " device=\"0\" if torch.cuda.is_available() else \"cpu\",\n",
1506
- " workers=2,\n",
1507
  " amp=True,\n",
 
 
1508
  " plots=True,\n",
1509
  " save=True,\n",
1510
  " verbose=True,\n",
 
56
  "\n",
57
  "- 阀门标签默认使用 HuggingFace 上的 `reviewed_labels/valve`。\n",
58
  "- 之前失败的整图阀门自动标注模式不会默认参与训练。\n",
59
+ "- 训练默认优先从 HuggingFace 最新 `best.pt` 继续微调;没有历史权重时使用 `yolo11x-seg.pt`。\n",
60
+ "- 训练集构建时会把超大原图生成 1600 长边以内的高质量 JPG 副本,减少 Colab 反复解码大 PNG 的时间。\n",
61
+ "- 训练默认使用图片尺寸 640、自动 batch、训练/验证/测试 70/15/15 划分。\n",
62
  "- 生成的标签和训练结果默认上传回同一个数据集仓库。"
63
  ]
64
  },
 
105
  " HfApi,\n",
106
  " login,\n",
107
  " snapshot_download,\n",
108
+ " hf_hub_download,\n",
109
  " CommitOperationAdd,\n",
110
  ")\n",
111
  "\n",
 
1069
  "\n",
1070
  "training_manifest_rows: list[dict] = []\n",
1071
  "\n",
1072
+ "TRAIN_IMAGE_MAX_SIDE = 1600\n",
1073
+ "TRAIN_IMAGE_JPEG_QUALITY = 95\n",
1074
+ "\n",
1075
+ "\n",
1076
+ "def write_training_image(src: Path, dst: Path) -> None:\n",
1077
+ " \"\"\"Create a training-sized JPG copy while preserving aspect ratio.\"\"\"\n",
1078
+ " img = cv2.imread(str(src), cv2.IMREAD_COLOR)\n",
1079
+ " if img is None:\n",
1080
+ " raise RuntimeError(f\"Failed to read source image: {src}\")\n",
1081
+ "\n",
1082
+ " h, w = img.shape[:2]\n",
1083
+ " max_side = max(h, w)\n",
1084
+ " if TRAIN_IMAGE_MAX_SIDE and max_side > TRAIN_IMAGE_MAX_SIDE:\n",
1085
+ " scale = TRAIN_IMAGE_MAX_SIDE / max_side\n",
1086
+ " new_size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))\n",
1087
+ " img = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)\n",
1088
+ "\n",
1089
+ " ok = cv2.imwrite(\n",
1090
+ " str(dst),\n",
1091
+ " img,\n",
1092
+ " [int(cv2.IMWRITE_JPEG_QUALITY), TRAIN_IMAGE_JPEG_QUALITY],\n",
1093
+ " )\n",
1094
+ " if not ok:\n",
1095
+ " raise RuntimeError(f\"Failed to write training image: {dst}\")\n",
1096
+ "\n",
1097
  "\n",
1098
  "def materialize(split: str, split_samples: list[dict]) -> None:\n",
1099
  " for idx, sample in enumerate(split_samples, 1):\n",
 
1100
  " stem = f\"{sample['source']}_{idx:05d}\"\n",
1101
+ " dst_img = COMBINED_DATASET / f\"images/{split}/{stem}.jpg\"\n",
1102
  " dst_lbl = COMBINED_DATASET / f\"labels/{split}/{stem}.txt\"\n",
1103
+ " write_training_image(sample[\"image\"], dst_img)\n",
1104
  " write_lines(dst_lbl, sample[\"lines\"])\n",
1105
  " training_manifest_rows.append({\n",
1106
  " \"split\": split,\n",
1107
  " \"dataset_stem\": stem,\n",
1108
  " \"image_path\": str(dst_img),\n",
1109
  " \"label_path\": str(dst_lbl),\n",
1110
+ " \"source_image_path\": str(sample[\"image\"]),\n",
1111
  " \"source_key\": sample[\"source_key\"],\n",
1112
  " \"source\": sample[\"source\"],\n",
1113
  " \"source_stem\": sample[\"source_stem\"],\n",
 
1120
  "materialize(\"train\", train_samples)\n",
1121
  "materialize(\"val\", val_samples)\n",
1122
  "materialize(\"test\", test_samples)\n",
1123
+ "\n",
1124
+ "image_bytes = sum(p.stat().st_size for p in (COMBINED_DATASET / \"images\").rglob(\"*\") if p.is_file())\n",
1125
+ "print(f\"Materialized training images as JPG, max_side={TRAIN_IMAGE_MAX_SIDE}, total={image_bytes / 1024 / 1024:.1f} MB\")\n",
1126
  "pd.DataFrame(training_manifest_rows).to_csv(\n",
1127
  " COMBINED_MANIFEST_PATH,\n",
1128
  " index=False,\n",
 
1444
  "outputs": [],
1445
  "source": [
1446
  "# @title Step 12 - 训练 YOLO-seg\n",
1447
+ "# @markdown 默认使用快速高精度微调:优先从 HuggingFace 最新 best.pt 继续训练;没有历史权重时再从 yolo11x-seg.pt 冷启动。\n",
1448
  "\n",
1449
  "from ultralytics import YOLO\n",
1450
  "\n",
1451
+ "BASE_TRAIN_MODEL = \"yolo11x-seg.pt\" # 保持高精度模型,不降到小模型。\n",
1452
+ "PREFER_HF_BEST_WARM_START = True # 优先加载上一轮 best.pt 微调,减少重复训练时间。\n",
1453
+ "WARM_START_RUN_NAME = \"\" # 留空时自动选择最新 gas_valve_seg_reviewed_* run。\n",
1454
+ "WARM_START_EPOCHS = 40 # 从已有 best.pt 微调时一般不需要再跑 120 轮。\n",
1455
+ "COLD_START_EPOCHS = 60 # 没有历史权重时的冷启动轮数。\n",
1456
+ "IMG_SIZE = 640 # YOLO 分割常用图片尺寸。\n",
1457
+ "BATCH = 0.90 # 使用约 90% GPU 显存自动选择 batch,比 -1 通常更充分。\n",
1458
+ "PATIENCE = 15 # 验证集 15 轮不提升就早停。\n",
1459
+ "WORKERS = 4 # Colab T4 场景下 4 个 dataloader workers 通常比 2 更高效。\n",
1460
+ "CACHE_IMAGES = \"disk\" # 缓存训练图片,避免每轮反复解码大图;比 RAM 缓存更稳。\n",
1461
+ "DETERMINISTIC = False # 不强制完全确定性,换取 cuDNN 更快算法。\n",
1462
  "RUN_NAME = f\"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}\"\n",
1463
  "AUTO_UPLOAD_TRAINING_RESULTS = True\n",
1464
  "\n",
1465
+ "\n",
1466
+ "def resolve_train_model() -> tuple[str, bool, str]:\n",
1467
+ " if not PREFER_HF_BEST_WARM_START:\n",
1468
+ " return BASE_TRAIN_MODEL, False, \"disabled\"\n",
1469
+ "\n",
1470
+ " try:\n",
1471
+ " remote_files = api.list_repo_files(DATASET_REPO, repo_type=\"dataset\", token=HF_TOKEN)\n",
1472
+ " if WARM_START_RUN_NAME:\n",
1473
+ " candidate_runs = [WARM_START_RUN_NAME]\n",
1474
+ " else:\n",
1475
+ " candidate_runs = sorted({\n",
1476
+ " f.split(\"/\")[1]\n",
1477
+ " for f in remote_files\n",
1478
+ " if f.startswith(\"runs/gas_valve_seg_reviewed_\")\n",
1479
+ " and f.endswith(\"/weights/best.pt\")\n",
1480
+ " }, reverse=True)\n",
1481
+ "\n",
1482
+ " for run in candidate_runs:\n",
1483
+ " filename = f\"runs/{run}/weights/best.pt\"\n",
1484
+ " if filename not in remote_files:\n",
1485
+ " continue\n",
1486
+ " local_path = hf_hub_download(\n",
1487
+ " repo_id=DATASET_REPO,\n",
1488
+ " repo_type=\"dataset\",\n",
1489
+ " token=HF_TOKEN,\n",
1490
+ " filename=filename,\n",
1491
+ " local_dir=\"/content/hf_training_weights\",\n",
1492
+ " )\n",
1493
+ " return local_path, True, run\n",
1494
+ " except Exception as exc:\n",
1495
+ " print(\"历史 best.pt 下载失败,将使用基础预训练权重冷启动。\")\n",
1496
+ " print(repr(exc))\n",
1497
+ "\n",
1498
+ " return BASE_TRAIN_MODEL, False, \"not_found\"\n",
1499
+ "\n",
1500
+ "\n",
1501
+ "TRAIN_MODEL, IS_WARM_START, WARM_START_SOURCE = resolve_train_model()\n",
1502
+ "EPOCHS = WARM_START_EPOCHS if IS_WARM_START else COLD_START_EPOCHS\n",
1503
+ "\n",
1504
  "print(\"训练参数\")\n",
1505
  "print(f\" model: {TRAIN_MODEL}\")\n",
1506
+ "print(f\" warm_start: {IS_WARM_START} ({WARM_START_SOURCE})\")\n",
1507
  "print(f\" data: {YAML_PATH}\")\n",
1508
  "print(f\" epochs: {EPOCHS}\")\n",
1509
  "print(f\" imgsz: {IMG_SIZE}\")\n",
1510
  "print(f\" batch: {BATCH}\")\n",
1511
+ "print(f\" workers: {WORKERS}\")\n",
1512
+ "print(f\" cache: {CACHE_IMAGES}\")\n",
1513
+ "print(f\" deterministic: {DETERMINISTIC}\")\n",
1514
  "print(f\" run: {RUN_NAME}\")\n",
1515
  "\n",
1516
  "\n",
 
1573
  "\n",
1574
  "\n",
1575
  "model = YOLO(TRAIN_MODEL)\n",
1576
+ "if torch.cuda.is_available():\n",
1577
+ " torch.backends.cudnn.benchmark = True\n",
1578
+ " try:\n",
1579
+ " torch.set_float32_matmul_precision(\"high\")\n",
1580
+ " except Exception:\n",
1581
+ " pass\n",
1582
+ "\n",
1583
  "t_start = time.time()\n",
1584
  "train_results = model.train(\n",
1585
  " data=str(YAML_PATH),\n",
 
1590
  " project=\"/content/runs\",\n",
1591
  " name=RUN_NAME,\n",
1592
  " device=\"0\" if torch.cuda.is_available() else \"cpu\",\n",
1593
+ " workers=WORKERS,\n",
1594
  " amp=True,\n",
1595
+ " cache=CACHE_IMAGES,\n",
1596
+ " deterministic=DETERMINISTIC,\n",
1597
  " plots=True,\n",
1598
  " save=True,\n",
1599
  " verbose=True,\n",
colab/colab_gas_valve_auto_label_train.py CHANGED
@@ -43,7 +43,9 @@
43
  #
44
  # - 阀门标签默认使用 HuggingFace 上的 `reviewed_labels/valve`。
45
  # - 之前失败的整图阀门自动标注模式不会默认参与训练。
46
- # - 训练默认使用 `yolo11x-seg.pt`、120 轮、图片尺寸 640、自动 batch、训练/验证/测试 70/15/15 划分。
 
 
47
  # - 生成的标签和训练结果默认上传回同一个数据集仓库。
48
 
49
 
@@ -80,6 +82,7 @@ from huggingface_hub import (
80
  HfApi,
81
  login,
82
  snapshot_download,
 
83
  CommitOperationAdd,
84
  )
85
 
@@ -953,20 +956,45 @@ rng.shuffle(test_samples)
953
 
954
  training_manifest_rows: list[dict] = []
955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
956
 
957
  def materialize(split: str, split_samples: list[dict]) -> None:
958
  for idx, sample in enumerate(split_samples, 1):
959
- suffix = sample["image"].suffix.lower()
960
  stem = f"{sample['source']}_{idx:05d}"
961
- dst_img = COMBINED_DATASET / f"images/{split}/{stem}{suffix}"
962
  dst_lbl = COMBINED_DATASET / f"labels/{split}/{stem}.txt"
963
- shutil.copy2(sample["image"], dst_img)
964
  write_lines(dst_lbl, sample["lines"])
965
  training_manifest_rows.append({
966
  "split": split,
967
  "dataset_stem": stem,
968
  "image_path": str(dst_img),
969
  "label_path": str(dst_lbl),
 
970
  "source_key": sample["source_key"],
971
  "source": sample["source"],
972
  "source_stem": sample["source_stem"],
@@ -979,6 +1007,9 @@ def materialize(split: str, split_samples: list[dict]) -> None:
979
  materialize("train", train_samples)
980
  materialize("val", val_samples)
981
  materialize("test", test_samples)
 
 
 
982
  pd.DataFrame(training_manifest_rows).to_csv(
983
  COMBINED_MANIFEST_PATH,
984
  index=False,
@@ -1280,24 +1311,73 @@ display(widgets.VBox([
1280
 
1281
  # %%
1282
  # @title Step 12 - 训练 YOLO-seg
1283
- # @markdown 训练参数已经按本项目设置好:高精度模型、120 轮、图片尺寸 640、自动 batch。
1284
 
1285
  from ultralytics import YOLO
1286
 
1287
- TRAIN_MODEL = "yolo11x-seg.pt" # 优先保证精度。
1288
- EPOCHS = 120 # 最多训练 120 轮,早停可能提前结束。
1289
- IMG_SIZE = 640 # YOLO 分割常用图片尺寸。
1290
- BATCH = -1 # 让 Ultralytics 自动选择显存能承受的 batch。
1291
- PATIENCE = 35 # 验证集 35 轮不提升就早停。
 
 
 
 
 
 
1292
  RUN_NAME = f"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}"
1293
  AUTO_UPLOAD_TRAINING_RESULTS = True
1294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1295
  print("训练参数")
1296
  print(f" model: {TRAIN_MODEL}")
 
1297
  print(f" data: {YAML_PATH}")
1298
  print(f" epochs: {EPOCHS}")
1299
  print(f" imgsz: {IMG_SIZE}")
1300
  print(f" batch: {BATCH}")
 
 
 
1301
  print(f" run: {RUN_NAME}")
1302
 
1303
 
@@ -1360,6 +1440,13 @@ def upload_training_outputs(run_dir: Path, run_name: str) -> None:
1360
 
1361
 
1362
  model = YOLO(TRAIN_MODEL)
 
 
 
 
 
 
 
1363
  t_start = time.time()
1364
  train_results = model.train(
1365
  data=str(YAML_PATH),
@@ -1370,8 +1457,10 @@ train_results = model.train(
1370
  project="/content/runs",
1371
  name=RUN_NAME,
1372
  device="0" if torch.cuda.is_available() else "cpu",
1373
- workers=2,
1374
  amp=True,
 
 
1375
  plots=True,
1376
  save=True,
1377
  verbose=True,
 
43
  #
44
  # - 阀门标签默认使用 HuggingFace 上的 `reviewed_labels/valve`。
45
  # - 之前失败的整图阀门自动标注模式不会默认参与训练。
46
+ # - 训练默认优先从 HuggingFace 最新 `best.pt` 继续微调;没有历史权重时使用 `yolo11x-seg.pt`。
47
+ # - 训练集构建时会把超大原图生成 1600 长边以内的高质量 JPG 副本,减少 Colab 反复解码大 PNG 的时间。
48
+ # - 训练默认使用图片尺寸 640、自动 batch、训练/验证/测试 70/15/15 划分。
49
  # - 生成的标签和训练结果默认上传回同一个数据集仓库。
50
 
51
 
 
82
  HfApi,
83
  login,
84
  snapshot_download,
85
+ hf_hub_download,
86
  CommitOperationAdd,
87
  )
88
 
 
956
 
957
  training_manifest_rows: list[dict] = []
958
 
959
+ TRAIN_IMAGE_MAX_SIDE = 1600
960
+ TRAIN_IMAGE_JPEG_QUALITY = 95
961
+
962
+
963
+ def write_training_image(src: Path, dst: Path) -> None:
964
+ """Create a training-sized JPG copy while preserving aspect ratio."""
965
+ img = cv2.imread(str(src), cv2.IMREAD_COLOR)
966
+ if img is None:
967
+ raise RuntimeError(f"Failed to read source image: {src}")
968
+
969
+ h, w = img.shape[:2]
970
+ max_side = max(h, w)
971
+ if TRAIN_IMAGE_MAX_SIDE and max_side > TRAIN_IMAGE_MAX_SIDE:
972
+ scale = TRAIN_IMAGE_MAX_SIDE / max_side
973
+ new_size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))
974
+ img = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)
975
+
976
+ ok = cv2.imwrite(
977
+ str(dst),
978
+ img,
979
+ [int(cv2.IMWRITE_JPEG_QUALITY), TRAIN_IMAGE_JPEG_QUALITY],
980
+ )
981
+ if not ok:
982
+ raise RuntimeError(f"Failed to write training image: {dst}")
983
+
984
 
985
  def materialize(split: str, split_samples: list[dict]) -> None:
986
  for idx, sample in enumerate(split_samples, 1):
 
987
  stem = f"{sample['source']}_{idx:05d}"
988
+ dst_img = COMBINED_DATASET / f"images/{split}/{stem}.jpg"
989
  dst_lbl = COMBINED_DATASET / f"labels/{split}/{stem}.txt"
990
+ write_training_image(sample["image"], dst_img)
991
  write_lines(dst_lbl, sample["lines"])
992
  training_manifest_rows.append({
993
  "split": split,
994
  "dataset_stem": stem,
995
  "image_path": str(dst_img),
996
  "label_path": str(dst_lbl),
997
+ "source_image_path": str(sample["image"]),
998
  "source_key": sample["source_key"],
999
  "source": sample["source"],
1000
  "source_stem": sample["source_stem"],
 
1007
  materialize("train", train_samples)
1008
  materialize("val", val_samples)
1009
  materialize("test", test_samples)
1010
+
1011
+ image_bytes = sum(p.stat().st_size for p in (COMBINED_DATASET / "images").rglob("*") if p.is_file())
1012
+ print(f"Materialized training images as JPG, max_side={TRAIN_IMAGE_MAX_SIDE}, total={image_bytes / 1024 / 1024:.1f} MB")
1013
  pd.DataFrame(training_manifest_rows).to_csv(
1014
  COMBINED_MANIFEST_PATH,
1015
  index=False,
 
1311
 
1312
  # %%
1313
  # @title Step 12 - 训练 YOLO-seg
1314
+ # @markdown 默认使用快速高精度微调:优先从 HuggingFace 最新 best.pt 继续训练;没有历史权重时再从 yolo11x-seg.pt 冷启动。
1315
 
1316
  from ultralytics import YOLO
1317
 
1318
+ BASE_TRAIN_MODEL = "yolo11x-seg.pt" # 保持高精度模型,不降到小模型。
1319
+ PREFER_HF_BEST_WARM_START = True # 优先加载上一轮 best.pt 微调,减少重复训练时间。
1320
+ WARM_START_RUN_NAME = "" # 留空时自动选择最新 gas_valve_seg_reviewed_* run。
1321
+ WARM_START_EPOCHS = 40 # 从已有 best.pt 微调时一般不需要再跑 120 轮。
1322
+ COLD_START_EPOCHS = 60 # 没有历史权重时的冷启动轮数。
1323
+ IMG_SIZE = 640 # YOLO 分割常用图片尺寸。
1324
+ BATCH = 0.90 # 使用约 90% GPU 显存自动选择 batch,比 -1 通常更充分。
1325
+ PATIENCE = 15 # 验证集 15 轮不提升就早停。
1326
+ WORKERS = 4 # Colab T4 场景下 4 个 dataloader workers 通常比 2 更高效。
1327
+ CACHE_IMAGES = "disk" # 缓存训练图片,避免每轮反复解码大图;比 RAM 缓存更稳。
1328
+ DETERMINISTIC = False # 不强制完全确定性,换取 cuDNN 更快算法。
1329
  RUN_NAME = f"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}"
1330
  AUTO_UPLOAD_TRAINING_RESULTS = True
1331
 
1332
+
1333
+ def resolve_train_model() -> tuple[str, bool, str]:
1334
+ if not PREFER_HF_BEST_WARM_START:
1335
+ return BASE_TRAIN_MODEL, False, "disabled"
1336
+
1337
+ try:
1338
+ remote_files = api.list_repo_files(DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
1339
+ if WARM_START_RUN_NAME:
1340
+ candidate_runs = [WARM_START_RUN_NAME]
1341
+ else:
1342
+ candidate_runs = sorted({
1343
+ f.split("/")[1]
1344
+ for f in remote_files
1345
+ if f.startswith("runs/gas_valve_seg_reviewed_")
1346
+ and f.endswith("/weights/best.pt")
1347
+ }, reverse=True)
1348
+
1349
+ for run in candidate_runs:
1350
+ filename = f"runs/{run}/weights/best.pt"
1351
+ if filename not in remote_files:
1352
+ continue
1353
+ local_path = hf_hub_download(
1354
+ repo_id=DATASET_REPO,
1355
+ repo_type="dataset",
1356
+ token=HF_TOKEN,
1357
+ filename=filename,
1358
+ local_dir="/content/hf_training_weights",
1359
+ )
1360
+ return local_path, True, run
1361
+ except Exception as exc:
1362
+ print("历史 best.pt 下载失败,将使用基础预训练权重冷启动。")
1363
+ print(repr(exc))
1364
+
1365
+ return BASE_TRAIN_MODEL, False, "not_found"
1366
+
1367
+
1368
+ TRAIN_MODEL, IS_WARM_START, WARM_START_SOURCE = resolve_train_model()
1369
+ EPOCHS = WARM_START_EPOCHS if IS_WARM_START else COLD_START_EPOCHS
1370
+
1371
  print("训练参数")
1372
  print(f" model: {TRAIN_MODEL}")
1373
+ print(f" warm_start: {IS_WARM_START} ({WARM_START_SOURCE})")
1374
  print(f" data: {YAML_PATH}")
1375
  print(f" epochs: {EPOCHS}")
1376
  print(f" imgsz: {IMG_SIZE}")
1377
  print(f" batch: {BATCH}")
1378
+ print(f" workers: {WORKERS}")
1379
+ print(f" cache: {CACHE_IMAGES}")
1380
+ print(f" deterministic: {DETERMINISTIC}")
1381
  print(f" run: {RUN_NAME}")
1382
 
1383
 
 
1440
 
1441
 
1442
  model = YOLO(TRAIN_MODEL)
1443
+ if torch.cuda.is_available():
1444
+ torch.backends.cudnn.benchmark = True
1445
+ try:
1446
+ torch.set_float32_matmul_precision("high")
1447
+ except Exception:
1448
+ pass
1449
+
1450
  t_start = time.time()
1451
  train_results = model.train(
1452
  data=str(YAML_PATH),
 
1457
  project="/content/runs",
1458
  name=RUN_NAME,
1459
  device="0" if torch.cuda.is_available() else "cpu",
1460
+ workers=WORKERS,
1461
  amp=True,
1462
+ cache=CACHE_IMAGES,
1463
+ deterministic=DETERMINISTIC,
1464
  plots=True,
1465
  save=True,
1466
  verbose=True,