fix: 优化 nightly 流水线:单卡编译、统一 torch 安装、常规测试并发提速

Co-authored-by: yuaiming<yuaiming@h-partners.com>



# message auto-generated for no-merge-commit merge:
!47691 merge master into master

fix: 优化 nightly 流水线:单卡编译、统一 torch 安装、常规测试并发提速

Created-by: y30037164
Commit-by: yuaiming
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->

# 【合入来源】
https://gitcode.com/Ascend/pytorch/issues/5012

- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】
> 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\
> 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容)

# 【资料变更】
> 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及”

# 【接口变更】
> 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及”

# 【功能验证】
> 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\
> 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图

# 【CheckList】
> PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]

- [ ] 代码注释完备,正确记录错误日志
- [ ] 代码实现进行了返回值、空指针等校验
- [ ] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [ ] PR持续集成流水线(CI)执行通过,代码检查无异常


See merge request: Ascend/pytorch!47691
This commit is contained in:
y30037164
2026-10-10 18:01:48 +08:00
committed by ascend-robot
parent 709b3ea1a7
commit da62511fe6
7 changed files with 100 additions and 316 deletions
@@ -1,292 +0,0 @@
#!/usr/bin/env python3
"""
Install latest PyTorch nightly wheel from official website.
Fallback to a known stable version if fetch fails.
"""
import os
import re
import sys
import subprocess
from html.parser import HTMLParser
from datetime import datetime
KNOWN_URLS = {
(2, 13): "https://download-r2.pytorch.org/whl/cpu/torch-2.13.0%2Bcpu-cp310-cp310-manylinux_2_28_aarch64.whl",
(2, 14): (
"https://download-r2.pytorch.org/whl/nightly/cpu/"
"torch-2.14.0.dev20260811%2Bcpu-cp310-cp310-manylinux_2_28_aarch64.whl"
),
(2, 15): (
"https://download-r2.pytorch.org/whl/nightly/cpu/"
"torch-2.15.0.dev20260816%2Bcpu-cp310-cp310-manylinux_2_28_aarch64.whl"
),
}
class WheelParser(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for name, value in attrs:
if name == 'href' and value.endswith('.whl'):
self.links.append(value)
def get_version_from_filename(filename):
m = re.search(r'torch-(\d+)\.(\d+)', filename)
if m:
return (int(m.group(1)), int(m.group(2)))
return None
def get_target_version(branch):
if not branch or branch == 'master' or branch == 'main':
return None
m = re.search(r'(\d+)\.(\d+)', branch)
if m:
return (int(m.group(1)), int(m.group(2)))
return None
def get_known_url(target_version):
if target_version and target_version in KNOWN_URLS:
return KNOWN_URLS[target_version]
return None
def get_latest_url(url, arch='aarch64', python='cp310', variant='cpu', target_version=None):
print(f"Fetching {url}...")
for domain in ['download-r2.pytorch.org', 'download.pytorch.org']:
try:
req_url = url.replace('download.pytorch.org', domain)
result = subprocess.run(
['wget', '-q', '-O', '-', '--no-check-certificate', '--timeout=30', req_url],
capture_output=True, text=True, timeout=60
)
if result.returncode == 0 and result.stdout:
html = result.stdout
print(f"Page fetched successfully from {domain}")
break
except Exception as e:
print(f"Failed to fetch from {domain}: {e}")
continue
else:
print("Failed to fetch from all domains (network error)")
return None
parser = WheelParser()
parser.feed(html)
print(f"Found {len(parser.links)} wheels on page")
all_versions = set()
for link in parser.links:
ver = get_version_from_filename(link)
if ver:
all_versions.add(f"{ver[0]}.{ver[1]}")
print(f"Available versions on page: {sorted(all_versions)}")
if target_version:
version_str = f"{target_version[0]}.{target_version[1]}"
print(f"Looking for version: {version_str}")
if version_str not in all_versions:
print(f"ERROR: Version {version_str} not found on page")
print(f"ERROR: Available versions: {sorted(all_versions)}")
return None
candidates = []
for link in parser.links:
if arch not in link or python not in link or variant not in link:
continue
if 'linux' not in link and 'manylinux' not in link:
continue
ver = get_version_from_filename(link)
if target_version and ver != target_version:
continue
m = re.search(r'(\d{8})', link)
if m:
try:
date = datetime.strptime(m.group(1), '%Y%m%d')
candidates.append((date, link))
except ValueError:
pass
if not candidates:
print(f"No matching wheel found after filtering (arch={arch}, python={python}, variant={variant})")
return None
candidates.sort(key=lambda x: x[0], reverse=True)
best = candidates[0][1]
ver = get_version_from_filename(best)
if ver:
print(f"Matched PyTorch {ver[0]}.{ver[1]} (latest nightly)")
if best.startswith('http'):
return best
return f"https://download.pytorch.org/whl/nightly/torch/{best}"
def get_stable_url(arch='aarch64', python='cp310', variant='cpu', target_version=None):
if not target_version:
return None
stable_url = f"https://download.pytorch.org/whl/{variant}/"
print(f"Trying stable version from {stable_url}...")
for domain in ['download.pytorch.org', 'download-r2.pytorch.org']:
try:
req_url = stable_url.replace('download.pytorch.org', domain)
result = subprocess.run(
['wget', '-q', '-O', '-', '--no-check-certificate', '--timeout=60', req_url],
capture_output=True, text=True, timeout=120
)
if result.returncode == 0 and result.stdout:
html = result.stdout
break
except Exception as e:
continue
else:
print("Failed to fetch stable page")
return None
parser = WheelParser()
parser.feed(html)
print(f"Found {len(parser.links)} wheels in stable")
candidates = []
for link in parser.links:
if arch in link and python in link and variant in link:
if 'linux' in link or 'manylinux' in link:
ver = get_version_from_filename(link)
if ver == target_version:
candidates.append(link)
if not candidates:
print(f"No stable wheel found for PyTorch {target_version[0]}.{target_version[1]}")
return None
print(f"Found stable wheel: {candidates[0]}")
return candidates[0]
def download(url, output_path):
print(f"Downloading to {output_path}...")
urls = [url]
if 'download-r2.pytorch.org' in url:
urls.append(url.replace('download-r2.pytorch.org', 'download.pytorch.org'))
for i, u in enumerate(urls):
if i > 0:
print("Trying main domain...")
result = subprocess.run(
['wget', '--no-check-certificate', '--tries=3', '--retry-connrefused',
'--timeout=120', '-q', '-O', output_path, u],
capture_output=True, text=True
)
if result.returncode == 0 and os.path.exists(output_path):
size = os.path.getsize(output_path) / 1024 / 1024
print(f"OK ({size:.1f} MB)")
return True
if os.path.exists(output_path):
os.remove(output_path)
return False
def install(wheel_path, python='python3.10'):
print(f"Installing {os.path.basename(wheel_path)}...")
result = subprocess.run(
[python, '-m', 'pip', 'install', '--no-deps', wheel_path],
capture_output=True, text=True
)
if result.returncode == 0:
print("Installed successfully")
return True
else:
print(f"Failed: {result.stderr}")
return False
def get_filename_from_url(url):
from urllib.parse import unquote
filename = url.split('/')[-1]
return unquote(filename)
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--arch', default='aarch64')
parser.add_argument('--python-tag', default='cp310')
parser.add_argument('--variant', default='cpu')
parser.add_argument('--python-exe', default='python3.10')
parser.add_argument('--branch', default='master')
args = parser.parse_args()
target_version = get_target_version(args.branch)
ver_str = f"{target_version[0]}.{target_version[1]}" if target_version else "latest"
print(f"Installing PyTorch {ver_str} (arch={args.arch}, python={args.python_tag})")
known_url = get_known_url(target_version)
if known_url:
print(f"Trying hardcoded URL for version {ver_str}...")
filename = get_filename_from_url(known_url)
out_path = os.path.join('.', filename)
if download(known_url, out_path) and install(out_path, args.python_exe):
verify_and_exit(args.python_exe)
print("Hardcoded URL failed, crawling page...")
print("Crawling PyTorch website...")
latest_url = get_latest_url(
'https://download.pytorch.org/whl/nightly/torch/',
args.arch, args.python_tag, args.variant,
target_version=target_version
)
if not latest_url and target_version:
print("Nightly not found, trying stable...")
latest_url = get_stable_url(
args.arch, args.python_tag, args.variant,
target_version=target_version
)
if latest_url:
filename = get_filename_from_url(latest_url)
out_path = os.path.join('.', filename)
print(f"Found: {filename}")
if download(latest_url, out_path) and install(out_path, args.python_exe):
verify_and_exit(args.python_exe)
print("FAILED: Could not install PyTorch")
sys.exit(1)
def verify_and_exit(python_exe):
# 不做 import torch 验证: 无卡编译机上镜像预装的是 NPU 版 torch, import 会段错误
# (与 PR build_job.yml 一致, 编译走 stub 库不依赖 import torch 成功)
r = subprocess.run(
[python_exe, '-m', 'pip', 'show', 'torch'],
capture_output=True, text=True
)
if r.returncode != 0:
print("FAILED: pip show torch failed")
sys.exit(1)
print("SUCCESS: PyTorch installed")
sys.exit(0)
if __name__ == '__main__':
main()
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""按 PR build_job.yml 的方式安装 PyTorch: 从 requirements.txt 读版本并走 OBS 源。"""
import os
import re
import sys
import subprocess
def install_from_requirements(python_exe='python3.10', arch='aarch64', python_tag='cp310'):
req_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'..', '..', 'requirements.txt')
torch_version = None
with open(req_path, encoding='utf-8') as f:
for line in f:
line = line.strip()
if line.startswith('torch=='):
torch_version = line[len('torch=='):].strip()
break
if not torch_version:
print("FAILED: torch== not found in requirements.txt")
return False
base_version = torch_version.split('+')[0] # e.g. 2.15.0.dev20260902
date_match = re.search(r'(\d{8})$', base_version)
if date_match:
ver = base_version
url_base = ("https://pytorch-package.obs.cn-north-4.myhuaweicloud.com"
f"/pta/torch/master/{date_match.group(1)}")
else:
ver = base_version
url_base = ("https://pytorch-package.obs.cn-north-4.myhuaweicloud.com"
f"/pta/torch/v{ver}")
if arch in ('x64', 'x86', 'x86_64'):
torch_arch = 'x86_64'
elif arch in ('arm64', 'arm'):
torch_arch = 'aarch64'
else:
torch_arch = arch
torch_url = (f"{url_base}/torch-{ver}%2Bcpu-{python_tag}-{python_tag}"
f"-manylinux_2_28_{torch_arch}.whl")
print(f"torch_url={torch_url}")
print(f"Installing via pip: {torch_url}")
result = subprocess.run([python_exe, '-m', 'pip', 'install', torch_url])
return result.returncode == 0
def verify(python_exe):
r = subprocess.run(
[python_exe, '-m', 'pip', 'show', 'torch'],
capture_output=True, text=True
)
if r.returncode != 0:
print("FAILED: pip show torch failed")
return False
print("SUCCESS: PyTorch installed")
return True
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--arch', default='aarch64')
parser.add_argument('--python-tag', default='cp310')
parser.add_argument('--python-exe', default='python3.10')
args = parser.parse_args()
if not install_from_requirements(args.python_exe, args.arch, args.python_tag):
print("FAILED: Could not install PyTorch")
sys.exit(1)
if not verify(args.python_exe):
sys.exit(1)
if __name__ == '__main__':
main()
@@ -616,13 +616,14 @@ def run_tests_with_tasks_concurrent(
})
# Execute batches via ThreadPoolExecutor.
# 按设备组分串行队列:同一组卡(相同取模余数)的 batch 必须串行,否则某组卡上
# 的 batch 先跑完时,空闲 worker 会立即调度到同组卡的下一个 batch,造成同卡
# 并发争抢(显存/算力冲突、超时/结果不稳定)。
# 按设备组分并发队列:同一组卡(相同取模余数)的 batch 用同一把信号量限流,
# 容量 = max_workers,即同一组卡上最多 max_workers 个 batch 并发。
# 多卡时各组卡可并行;单卡时 dev_groups=1,等价于全局 max_workers 并发,
# 并发上限由 --max-workers 控制。
dev_groups = 0
if num_npu_devices is not None:
dev_groups = max(1, num_npu_devices // cards_per_test) if cards_per_test > 0 else num_npu_devices
group_locks = [threading.Lock() for _ in range(dev_groups)]
group_semaphores = [threading.Semaphore(max_workers) for _ in range(dev_groups)]
def _execute_one(batch, batch_id):
# Calculate device ID:
@@ -643,7 +644,7 @@ def run_tests_with_tasks_concurrent(
shard, shard_type, device_id, result_aggregator, progress_tracker, log_queue,
)
if dev_groups:
with group_locks[batch_id % dev_groups]:
with group_semaphores[batch_id % dev_groups]:
_execute_worker_batch(*worker_args)
else:
_execute_worker_batch(*worker_args)
+4 -6
View File
@@ -43,7 +43,7 @@ jobs:
build:
name: build
select: selected_by_default
runs-on: [ self-hosted, op_plugin, "${{ inputs.RUNS_ON_ARCH }}", "${{ inputs.RUNS_ON_SPEC }}" ]
runs-on: [ self-hosted, "${{ inputs.RUNS_ON_SPEC }}" ]
container:
image: ${{ inputs.DOCKER_IMAGE }}
options: ${{ inputs.CONTAINER_OPTIONS }}
@@ -68,14 +68,12 @@ jobs:
ccache --version | head -1 >> build_msg.txt
echo "=== Build Info End ===" >> build_msg.txt
- name: Install PyTorch from official website
- name: Install PyTorch
run: |
python3.10 .gitcode/scripts/install_pytorch_from_official.py \
python3.10 .gitcode/scripts/install_pytorch_from_requirements.py \
--arch aarch64 \
--python-tag cp310 \
--variant cpu \
--python-exe python3.10 \
--branch "${{ inputs.PYTORCH_BRANCH }}"
--python-exe python3.10
- name: Install nanobind
run: |
+3 -5
View File
@@ -51,14 +51,12 @@ jobs:
- name: checkout
uses: checkout
- name: Install latest PyTorch from official website
- name: Install PyTorch
run: |
python3.10 .gitcode/scripts/install_pytorch_from_official.py \
python3.10 .gitcode/scripts/install_pytorch_from_requirements.py \
--arch aarch64 \
--python-tag cp310 \
--variant cpu \
--python-exe python3.10 \
--branch "${{ inputs.PYTORCH_BRANCH }}"
--python-exe python3.10
- name: Install pytest-timeout
run: python3.10 -m pip install --trusted-host mirrors.huaweicloud.com pytest-timeout
+3 -5
View File
@@ -75,14 +75,12 @@ jobs:
name: torch-npu-wheel
path: ./
- name: Install latest PyTorch from official website
- name: Install PyTorch
run: |
python3.10 .gitcode/scripts/install_pytorch_from_official.py \
python3.10 .gitcode/scripts/install_pytorch_from_requirements.py \
--arch aarch64 \
--python-tag cp310 \
--variant cpu \
--python-exe python3.10 \
--branch "${{ inputs.PYTORCH_BRANCH }}"
--python-exe python3.10
- name: Install pytest-timeout
run: python3.10 -m pip install --trusted-host mirrors.huaweicloud.com pytest-timeout
@@ -22,7 +22,7 @@ on:
- ".gitcode/workflows/_nightly_collect.yml"
- ".gitcode/workflows/_nightly_test_job.yml"
- ".gitcode/workflows/_nightly_report.yml"
- ".gitcode/scripts/install_pytorch_from_official.py"
- ".gitcode/scripts/install_pytorch_from_requirements.py"
- ".gitcode/scripts/setup_npu_test_env.sh"
- ".gitcode/scripts/collect_all_cases.py"
- ".gitcode/scripts/discover_test_files.py"
@@ -40,7 +40,7 @@ env:
PYTHON_VERSION: "3.10"
# ── 运行参数 ──
CASE_TIMEOUT: "1200"
REG_WORKERS: "16"
REG_WORKERS: "4"
COLLECT_PARALLEL: "16"
MAX_JOBS: "128"
# ── 分片配置 ──
@@ -51,6 +51,7 @@ env:
DOCKER_BASE_IMAGE: "swr.cn-north-4.myhuaweicloud.com/frameworkptadapter/pytorch_master_a2_aarch64_builder:20260922"
# ── 容器选项 ──
CONTAINER_OPTS_BUILD: "--user root"
CONTAINER_OPTS_BUILD_NPU: "--user root --volume /usr/local/Ascend:/usr/local/Ascend --volume /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi --device /dev/davinci0 --device /dev/davinci_manager --device /dev/hisi_hdc --device /dev/devmm_svm"
CONTAINER_OPTS_NPU: "--user root --volume /usr/local/Ascend:/usr/local/Ascend --volume /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi --device /dev/davinci0 --device /dev/davinci1 --device /dev/davinci2 --device /dev/davinci3 --device /dev/davinci4 --device /dev/davinci5 --device /dev/davinci6 --device /dev/davinci7 --device /dev/davinci_manager --device /dev/hisi_hdc --device /dev/devmm_svm"
CONTAINER_OPTS_COLLECT: "--user root --volume /usr/local/Ascend:/usr/local/Ascend --volume /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi --device /dev/davinci0 --device /dev/davinci1 --device /dev/davinci2 --device /dev/davinci3 --device /dev/davinci4 --device /dev/davinci5 --device /dev/davinci6 --device /dev/davinci7 --device /dev/davinci_manager --device /dev/hisi_hdc --device /dev/devmm_svm"
CONTAINER_OPTS_LIGHT: "--user root"
@@ -78,8 +79,9 @@ stages:
MAX_JOBS: ${{ env.MAX_JOBS }}
TORCH_NPU_WHEEL_ARTIFACT_DIR: ${{ env.TORCH_NPU_WHEEL_ARTIFACT_DIR }}
DOCKER_IMAGE: ${{ env.DOCKER_BASE_IMAGE }}
CONTAINER_OPTIONS: ${{ env.CONTAINER_OPTS_BUILD }}
CONTAINER_OPTIONS: ${{ env.CONTAINER_OPTS_BUILD_NPU }}
RUNS_ON_ARCH: ${{ env.BUILD_ARCH }}
RUNS_ON_SPEC: ${{ env.NPU_LABEL_REG }}
# Stage 2: 采集 + 分片
stage_collect: