Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions exir/_serialize/_program.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,7 @@ def _extract_delegate_segments(
"""
remaining_inline: List[BackendDelegateInlineData] = []
inline_indices_seen: set[int] = set()
segment_index_map: dict[bytes, int] = {}
for plan in program.execution_plan:
for delegate in plan.delegates:
if delegate.processed.location != DataLocation.INLINE:
Expand All@@ -249,8 +250,11 @@ def _extract_delegate_segments(
inline_indices_seen.add(delegate.processed.index)
if inline.data:
# Move the delegate data out of the program.
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index = segment_index_map.get(inline.data)
if segment_index is None:
segment_index = len(segments)
segments.append(Cord(inline.data))
segment_index_map[inline.data] = segment_index
delegate.processed = BackendDelegateDataReference(
location=DataLocation.SEGMENT,
index=segment_index,
Expand Down
1 change: 1 addition & 0 deletions exir/backend/test/demos/rpc/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ runtime.python_library(
],
visibility = [
"//executorch/exir/backend/test/...",
"//executorch/exir/emit/test/...",
],
deps = [
":executor_backend_preprocess",
Expand Down
23 changes: 16 additions & 7 deletions exir/emit/_emitter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -122,6 +122,8 @@ class _ProgramState:
# Delegate data stored directly in the flatbuffer. Pointed to by BackendDelegateDataReference,
# and should be copied to Program.backend_delegate_data.
backend_delegate_data: List[BackendDelegateInlineData] = field(default_factory=list)
# Delegate cache that is used across all entry points. Key is the hash of the delegated payload.
backend_delegate_data_cache: Dict[str, int] = field(default_factory=dict)

# Constants are optionally stored in external files.
# Aggregate unique external constants into one buffer.
Expand All@@ -144,7 +146,8 @@ class _EmitterState:
operators: List[Operator]
delegates: List[BackendDelegate]
operator_cache: Dict[Tuple[str, str], int]
delegate_cache: Dict[bytes, int]
# delegate_cache: the key is hash(delegated_payload) and the value is the index in delegates
delegate_cache: Dict[str, int]
emit_stacktrace: bool

spec2id_dict: Dict[TensorSpec, int] = field(default_factory=dict)
Expand DownExpand Up@@ -1073,8 +1076,8 @@ def _emit_delegate(
"""Emit the delegates inputs and outputs as specified by the schema, then emit the
delegate's blob."""
processed_bytes = lowered_module.processed_bytes

delegate_index = self.emitter_state.delegate_cache.get(processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
delegate_index = self.emitter_state.delegate_cache.get(hashed)
delegate_ret = None

if isinstance(self.node.meta["spec"], list):
Expand DownExpand Up@@ -1112,10 +1115,16 @@ def _emit_delegate(
if delegate_index is None:
# Allocate an entry for the data. TODO(T150113674): Reuse any duplicate entries if
# present.
data_index: int = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
hashed = hashlib.sha256(processed_bytes).hexdigest()
data_index: Optional[int] = (
self.program_state.backend_delegate_data_cache.get(hashed)
)
if data_index is None:
data_index = len(self.program_state.backend_delegate_data)
self.program_state.backend_delegate_data_cache[hashed] = data_index
self.program_state.backend_delegate_data.append(
BackendDelegateInlineData(data=processed_bytes)
)

backend_delegate = BackendDelegate(
id=lowered_module.backend_id,
Expand All@@ -1126,7 +1135,7 @@ def _emit_delegate(
)
delegate_index = len(self.emitter_state.delegate_cache)
self.emitter_state.delegates.append(backend_delegate)
self.emitter_state.delegate_cache[processed_bytes] = delegate_index
self.emitter_state.delegate_cache[hashed] = delegate_index

# TODO(angelayi) Will need to emit the kwargs too, in the correct order according to the
# function's spec and with default arguments. This requires us to store the function's spec
Expand Down
1 change: 1 addition & 0 deletions exir/emit/test/TARGETS
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ python_unittest(
"//executorch/exir:lib",
"//executorch/exir:print_program",
"//executorch/exir:schema",
"//executorch/exir/backend/test/demos/rpc:executor_backend_partitioner",
"//executorch/exir/backend:backend_api",
"//executorch/exir/emit:lib",
"//executorch/exir/passes:const_prop_pass",
Expand Down
56 changes: 55 additions & 1 deletion exir/emit/test/test_emit.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,9 @@
from executorch.exir._serialize._program import deserialize_pte_binary
from executorch.exir.backend.backend_api import to_backend
from executorch.exir.backend.backend_details import BackendDetails, PreprocessResult
from executorch.exir.backend.test.demos.rpc.executor_backend_partitioner import (
ExecutorBackendPartitioner,
)
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.emit import emit_program # noqa
from executorch.exir.error import InternalError
Expand DownExpand Up@@ -63,7 +66,7 @@
from functorch.experimental import control_flow
from torch import nn

from torch.export import Dim, export
from torch.export import Dim, export, export_for_training


class WrapperModule(torch.nn.Module):
Expand DownExpand Up@@ -1679,3 +1682,54 @@ def forward(self, x):
]
self.assertEqual(external_map["linear.weight"], 0)
self.assertEqual(external_map["linear.bias"], 1)

def test_delegate_deduplicate(self) -> None:
class SharedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(2, 2)

def forward(self, x):
return self.linear(x)

class Module1(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

class Module2(torch.nn.Module):
def __init__(self, shared_module):
super().__init__()
self.shared_module = shared_module

def forward(self, x):
return self.shared_module(x)

shared_module = SharedModule()
module_1 = Module1(shared_module)
module_2 = Module2(shared_module)
example_inputs = (torch.randn(2, 2),)
module_1(*example_inputs)
module_2(*example_inputs)

ep1 = export_for_training(module_1, example_inputs)
ep2 = export_for_training(module_2, example_inputs)

edge_program_manager = exir.to_edge(
{"forward1": ep1, "forward2": ep2},
compile_config=exir.EdgeCompileConfig(
_check_ir_validity=False, _use_edge_ops=True
),
)

edge_program_manager = edge_program_manager.to_backend(
ExecutorBackendPartitioner()
).to_executorch()

# Check that there is only one delegate because two methods are exactly the same
self.assertEqual(
len(edge_program_manager.executorch_program.backend_delegate_data), 1
)