Skip to content

Commit 9d69769

Browse files
Update
[ghstack-poisoned]
2 parents 4367977 + f4d801a commit 9d69769

File tree

219 files changed

+7376
-2472
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

219 files changed

+7376
-2472
lines changed

.ci/docker/requirements-ci.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
mpmath==1.3.0
22
numpy>=2.0.0; python_version >= '3.10'
33
PyYAML==6.0.1
4-
ruamel.yaml==0.17.32
4+
ruamel.yaml==0.18.15
55
sympy==1.12
66
timm==0.6.13
77
tomli==2.0.1

.ci/scripts/test_llama_lora.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ cmake_build_llama_runner
5555
# Constants.
5656
RUNTIME_ARGS="--tokenizer_path=${DOWNLOADED_PATH}/tokenizer.model --temperature=0 --seq_len=20 --warmup=1"
5757
PROMPT="What happens if you eat watermelon seeds?"
58-
EXPECTED_PREFIX="What happens if you eat watermelon seeds? Watermelon seeds are a good source of vitamin C,"
58+
EXPECTED_PREFIX="What happens if you eat watermelon seeds? Watermelon seeds are a good source of vitamin C and"
5959

6060
# Export LoRA PTE file.
6161
MODEL_NAME="llama_3_2_1B_lora"

.githooks/pre-commit

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
#!/usr/bin/env bash
22

3-
# Pre-commit hook to automatically update PyTorch commit pin when torch_pin.py changes
3+
# Pre-commit hook to automatically update PyTorch commit pin and sync c10 directories when torch_pin.py changes
44

55
# Check if torch_pin.py is being committed
66
if git diff --cached --name-only | grep -q "^torch_pin.py$"; then
77
echo "🔍 Detected changes to torch_pin.py"
8-
echo "📝 Updating PyTorch commit pin..."
8+
echo "📝 Updating PyTorch commit pin and syncing c10 directories..."
99

10-
# Run the update script
10+
# Run the update script (which now also syncs c10 directories)
1111
if python .github/scripts/update_pytorch_pin.py; then
12-
# Check if pytorch.txt was modified
12+
# Stage any modified files (pytorch.txt and grafted c10 files)
1313
if ! git diff --quiet .ci/docker/ci_commit_pins/pytorch.txt; then
14-
echo "✅ PyTorch commit pin updated successfully"
15-
# Stage the updated file
1614
git add .ci/docker/ci_commit_pins/pytorch.txt
1715
echo "📌 Staged .ci/docker/ci_commit_pins/pytorch.txt"
18-
else
19-
echo "ℹ️ PyTorch commit pin unchanged"
16+
fi
17+
18+
# Stage any grafted c10 files
19+
if ! git diff --quiet runtime/core/portable_type/c10/; then
20+
git add runtime/core/portable_type/c10/
21+
echo "📌 Staged grafted c10 files"
2022
fi
2123
else
2224
echo "❌ Failed to update PyTorch commit pin"

.github/scripts/update_pytorch_pin.py

Lines changed: 157 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
#!/usr/bin/env python3
22

3+
import base64
4+
import hashlib
35
import json
46
import re
57
import sys
68
import urllib.request
7-
from datetime import datetime
9+
from pathlib import Path
810

911

1012
def parse_nightly_version(nightly_version):
@@ -53,7 +55,7 @@ def get_commit_hash_for_nightly(date_str):
5355
Commit hash string
5456
"""
5557
api_url = "https://api.github.com/repos/pytorch/pytorch/commits"
56-
params = f"?sha=nightly&per_page=100"
58+
params = f"?sha=nightly&per_page=50"
5759
url = api_url + params
5860

5961
req = urllib.request.Request(url)
@@ -74,14 +76,21 @@ def get_commit_hash_for_nightly(date_str):
7476
commit_msg = commit.get("commit", {}).get("message", "")
7577
# Check if the first line of commit message matches
7678
first_line = commit_msg.split("\n")[0].strip()
77-
if first_line == target_title or first_line.startswith(f"{date_str} nightly"):
78-
return commit["sha"]
79+
if first_line.startswith(f"{date_str} nightly"):
80+
return extract_hash_from_title(first_line)
7981

8082
raise ValueError(
8183
f"Could not find commit with title matching '{target_title}' in nightly branch"
8284
)
8385

8486

87+
def extract_hash_from_title(title):
88+
match = re.search(r"\(([0-9a-fA-F]{7,40})\)", title)
89+
if not match:
90+
raise ValueError(f"Could not extract commit hash from title '{title}'")
91+
return match.group(1)
92+
93+
8594
def update_pytorch_pin(commit_hash):
8695
"""
8796
Update .ci/docker/ci_commit_pins/pytorch.txt with the new commit hash.
@@ -95,6 +104,144 @@ def update_pytorch_pin(commit_hash):
95104
print(f"Updated {pin_file} with commit hash: {commit_hash}")
96105

97106

107+
def should_skip_file(filename):
108+
"""
109+
Check if a file should be skipped during sync (build files).
110+
111+
Args:
112+
filename: Base filename to check
113+
114+
Returns:
115+
True if file should be skipped
116+
"""
117+
skip_files = {"BUCK", "CMakeLists.txt", "TARGETS", "targets.bzl"}
118+
return filename in skip_files
119+
120+
121+
def fetch_file_content(commit_hash, file_path):
122+
"""
123+
Fetch file content from GitHub API.
124+
125+
Args:
126+
commit_hash: Commit hash to fetch from
127+
file_path: File path in the repository
128+
129+
Returns:
130+
File content as bytes
131+
"""
132+
api_url = f"https://api.github.com/repos/pytorch/pytorch/contents/{file_path}?ref={commit_hash}"
133+
134+
req = urllib.request.Request(api_url)
135+
req.add_header("Accept", "application/vnd.github.v3+json")
136+
req.add_header("User-Agent", "ExecuTorch-Bot")
137+
138+
try:
139+
with urllib.request.urlopen(req) as response:
140+
data = json.loads(response.read().decode())
141+
# Content is base64 encoded
142+
content = base64.b64decode(data["content"])
143+
return content
144+
except urllib.request.HTTPError as e:
145+
print(f"Error fetching file {file_path}: {e}", file=sys.stderr)
146+
raise
147+
148+
149+
def sync_directory(et_dir, pt_path, commit_hash):
150+
"""
151+
Sync files from PyTorch to ExecuTorch using GitHub API.
152+
Only syncs files that already exist in ExecuTorch - does not add new files.
153+
154+
Args:
155+
et_dir: ExecuTorch directory path
156+
pt_path: PyTorch directory path in the repository (e.g., "c10")
157+
commit_hash: Commit hash to fetch from
158+
159+
Returns:
160+
Number of files grafted
161+
"""
162+
files_grafted = 0
163+
print(f"Checking {et_dir} vs pytorch/{pt_path}...")
164+
165+
if not et_dir.exists():
166+
print(f"Warning: ExecuTorch directory {et_dir} does not exist, skipping")
167+
return 0
168+
169+
# Loop through files in ExecuTorch directory
170+
for et_file in et_dir.rglob("*"):
171+
if not et_file.is_file():
172+
continue
173+
174+
# Skip build files
175+
if should_skip_file(et_file.name):
176+
continue
177+
178+
# Construct corresponding path in PyTorch
179+
rel_path = et_file.relative_to(et_dir)
180+
pt_file_path = f"{pt_path}/{rel_path}".replace("\\", "/")
181+
182+
# Fetch content from PyTorch and compare
183+
try:
184+
pt_content = fetch_file_content(commit_hash, pt_file_path)
185+
et_content = et_file.read_bytes()
186+
187+
if pt_content != et_content:
188+
print(f"⚠️ Difference detected in {rel_path}")
189+
print(f"📋 Grafting from PyTorch commit {commit_hash}...")
190+
191+
et_file.write_bytes(pt_content)
192+
print(f"✅ Grafted {et_file}")
193+
files_grafted += 1
194+
except urllib.request.HTTPError as e:
195+
if e.code != 404: # It's ok to have more files in ET than pytorch/pytorch.
196+
print(f"Error fetching {rel_path} from PyTorch: {e}")
197+
except Exception as e:
198+
print(f"Error syncing {rel_path}: {e}")
199+
continue
200+
201+
return files_grafted
202+
203+
204+
def sync_c10_directories(commit_hash):
205+
"""
206+
Sync c10 and torch/headeronly directories from PyTorch to ExecuTorch using GitHub API.
207+
208+
Args:
209+
commit_hash: PyTorch commit hash to sync from
210+
211+
Returns:
212+
Total number of files grafted
213+
"""
214+
print("\n🔄 Syncing c10 directories from PyTorch via GitHub API...")
215+
216+
# Get repository root
217+
repo_root = Path.cwd()
218+
219+
# Define directory pairs to sync (from check_c10_sync.sh)
220+
# Format: (executorch_dir, pytorch_path_in_repo)
221+
dir_pairs = [
222+
(
223+
repo_root / "runtime/core/portable_type/c10/c10",
224+
"c10",
225+
),
226+
(
227+
repo_root / "runtime/core/portable_type/c10/torch/headeronly",
228+
"torch/headeronly",
229+
),
230+
]
231+
232+
total_grafted = 0
233+
for et_dir, pt_path in dir_pairs:
234+
files_grafted = sync_directory(et_dir, pt_path, commit_hash)
235+
total_grafted += files_grafted
236+
237+
if total_grafted > 0:
238+
print(f"\n✅ Successfully grafted {total_grafted} file(s) from PyTorch")
239+
else:
240+
print("\n✅ No differences found - c10 is in sync")
241+
242+
return total_grafted
243+
244+
98245
def main():
99246
try:
100247
# Read NIGHTLY_VERSION from torch_pin.py
@@ -112,7 +259,12 @@ def main():
112259
# Update the pin file
113260
update_pytorch_pin(commit_hash)
114261

115-
print("Successfully updated PyTorch commit pin!")
262+
# Sync c10 directories from PyTorch
263+
sync_c10_directories(commit_hash)
264+
265+
print(
266+
"\n✅ Successfully updated PyTorch commit pin and synced c10 directories!"
267+
)
116268

117269
except Exception as e:
118270
print(f"Error: {e}", file=sys.stderr)

.github/workflows/pull.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,7 @@ jobs:
892892
# Install test requirements
893893
pip install -r backends/nxp/requirements-tests-pypi.txt
894894
pip install -r backends/nxp/requirements-tests-eiq.txt
895+
PYTHON_EXECUTABLE=python bash examples/nxp/setup.sh
895896
896897
# Run pytest
897898
PYTHON_EXECUTABLE=python bash backends/nxp/run_unittests.sh

backends/aoti/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ include(${EXECUTORCH_ROOT}/tools/cmake/Utils.cmake)
2626
find_package_torch()
2727

2828
# Common AOTI functionality - combines all AOTI common components
29-
set(_aoti_common_sources aoti_model_container.cpp common_shims.cpp)
29+
set(_aoti_common_sources common_shims.cpp)
3030
add_library(aoti_common STATIC ${_aoti_common_sources})
3131
target_include_directories(
3232
aoti_common

backends/aoti/aoti_model_container.h renamed to backends/aoti/aoti_delegate_handle.h

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -60,36 +60,17 @@ using AOTInductorModelContainerRunFunc = AOTIRuntimeError (*)(
6060
AOTInductorStreamHandle stream_handle,
6161
AOTIProxyExecutorHandle proxy_executor_handle);
6262

63-
// Global function pointers (will be loaded dynamically)
64-
extern AOTInductorModelContainerCreateWithDeviceFunc
65-
AOTInductorModelContainerCreateWithDevice;
66-
extern AOTInductorModelContainerDeleteFunc AOTInductorModelContainerDelete;
67-
extern AOTInductorModelContainerGetNumInputsFunc
68-
AOTInductorModelContainerGetNumInputs;
69-
extern AOTInductorModelContainerGetNumOutputsFunc
70-
AOTInductorModelContainerGetNumOutputs;
71-
extern AOTInductorModelContainerRunFunc AOTInductorModelContainerRun;
72-
7363
// Retrieves the name of an input tensor by index from the AOTI model container.
74-
// Needed by Metal backend
7564
using AOTInductorModelContainerGetInputNameFunc = AOTIRuntimeError (*)(
7665
AOTInductorModelContainerHandle container_handle,
7766
size_t input_idx,
7867
const char** input_name);
7968

8069
// Retrieves the number of constants from the AOTI model container.
81-
// Needed by Metal backend
8270
using AOTInductorModelContainerGetNumConstantsFunc = AOTIRuntimeError (*)(
8371
AOTInductorModelContainerHandle container_handle,
8472
size_t* num_constants);
8573

86-
// Global function pointers (will be loaded dynamically).
87-
// Needed by Metal backend
88-
extern AOTInductorModelContainerGetInputNameFunc
89-
AOTInductorModelContainerGetInputName;
90-
extern AOTInductorModelContainerGetNumConstantsFunc
91-
AOTInductorModelContainerGetNumConstants;
92-
9374
} // extern "C"
9475

9576
// AOTI Delegate Handle structure
@@ -99,6 +80,13 @@ struct AOTIDelegateHandle {
9980
AOTInductorModelContainerHandle container_handle;
10081
void* cuda_stream; // cudaStream_t stored as void* to avoid CUDA header
10182
// dependency
83+
84+
// Function pointers specific to this handle's shared library
85+
AOTInductorModelContainerCreateWithDeviceFunc create_with_device;
86+
AOTInductorModelContainerDeleteFunc delete_container;
87+
AOTInductorModelContainerGetNumInputsFunc get_num_inputs;
88+
AOTInductorModelContainerGetNumOutputsFunc get_num_outputs;
89+
AOTInductorModelContainerRunFunc run;
10290
};
10391

10492
} // namespace aoti

backends/aoti/aoti_model_container.cpp

Lines changed: 0 additions & 39 deletions
This file was deleted.

backends/aoti/passes/TARGETS

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
load("@fbsource//xplat/executorch/build:runtime_wrapper.bzl", "runtime")
2+
3+
oncall("executorch")
4+
5+
runtime.python_library(
6+
name = "passes",
7+
srcs = [
8+
"replace_view_copy_with_view.py",
9+
],
10+
visibility = [
11+
"//executorch/...",
12+
],
13+
deps = [
14+
"//caffe2:torch",
15+
"//executorch/exir:pass_base",
16+
],
17+
)

0 commit comments

Comments
 (0)