Repository navigation
Commit e2bcb9d
authored
Serialize a program without copying its delegate blobs (pytorch#24458)
### What is wrong today
`to_executorch()` serializes the program right away. Before it moves
each delegate blob out of the program and into a segment,
`serialize_pte_binary` deep-copies the program, so that the caller's
program does not change.
`copy.deepcopy` shares an object whose type is exactly `bytes`. But it
copies an object of any other bytes type, for example a subclass of
`bytes`. The Core ML backend returns such a type for models over 1 GiB:
it maps the model files into memory instead of reading them. So for
these models, `to_executorch()` briefly held 2 more copies of the
delegate blob, and the serialized program kept 1 of them for as long as
the `ExecutorchProgramManager` lived.
With a 4 GiB delegate blob of a `bytes` subclass, peak memory in
`to_executorch()` grew by 8 GiB, and 4 GiB stayed in use after it
returned.
### What this change does
It seeds the `copy.deepcopy` memo with the delegate blobs, so the copied
program shares them instead of copying them. The blobs are immutable, so
sharing them is safe. The rest of the program is still copied, and the
output does not change.
### What was tested
- New test `test_serialize_shares_delegate_blobs` serializes a program
whose delegate blob is a `bytes` subclass, and checks that the output
holds that same object. It fails without this change.
- The `exir/_serialize` tests pass, and the other `exir` tests give the
same results with and without this change.
- A test backend whose `preprocess` returns a 4 GiB blob, on Linux
x86_64. With a `bytes` subclass, the extra peak memory in
`to_executorch()` went from 8 GiB to none, and the `.pte` file is byte
for byte the same as before. With plain `bytes`, nothing changed.1 parent 59541e1 commit e2bcb9d
2 files changed
Lines changed: 29 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
413 | 413 | | |
414 | 414 | | |
415 | 415 | | |
416 | | - | |
417 | | - | |
418 | | - | |
419 | | - | |
| 416 | + | |
| 417 | + | |
| 418 | + | |
| 419 | + | |
| 420 | + | |
| 421 | + | |
| 422 | + | |
| 423 | + | |
| 424 | + | |
| 425 | + | |
| 426 | + | |
420 | 427 | | |
421 | 428 | | |
422 | 429 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
777 | 777 | | |
778 | 778 | | |
779 | 779 | | |
| 780 | + | |
| 781 | + | |
| 782 | + | |
| 783 | + | |
| 784 | + | |
| 785 | + | |
| 786 | + | |
| 787 | + | |
| 788 | + | |
| 789 | + | |
| 790 | + | |
| 791 | + | |
| 792 | + | |
| 793 | + | |
| 794 | + | |
| 795 | + | |
| 796 | + | |
| 797 | + | |
780 | 798 | | |
781 | 799 | | |
782 | 800 | | |
| |||
0 commit comments