Skip to content

compiler cache not work #155332

@631068264

Description

@631068264

🐛 Describe the bug

In my program, I handle a batch of tasks, and I need to switch models dynamically based on task parameters.

I’m trying to compile a specific branch of the forward function in my Flux model. The idea is to run an inference once, then save the compiled result, using the model path as the cache key.

In practice, the compiled cache (in bytes) is successfully written to a file and can be loaded without errors. However, the inference time is almost the same as if no compilation had been used at all.

Is there something I might be missing when saving/loading the compiled cache? Or does the compilation not take effect as expected?

I have read this doc about how to use mega-cache but not work as I thought

my code run in multiprocessing

load.py load model in every process.

def get_artifact_path(ckpt_path: str) -> Path:
    ckpt_hash = hashlib.sha256(ckpt_path.encode()).hexdigest()
    return ARTIFACT_CACHE_DIR / f"{ckpt_hash}.artifact"


def save_cache_artifacts(ckpt_path):
    artifact_path = get_artifact_path(ckpt_path)
    if not artifact_path.exists():
        artifacts = torch.compiler.save_cache_artifacts()

        if artifacts is not None:
            artifact_bytes, cache_info = artifacts
            if len(artifact_bytes) > 8:  # ensure not empty
                artifact_path.write_bytes(artifact_bytes)
                print(f"[Cache] Saved compiler cache to {artifact_path}")
                return

        print("[Warning] No artifacts were saved!")


def torch_compile(model, ckpt_path: str):
    artifact_path = get_artifact_path(ckpt_path)
    if artifact_path.exists():
        print(f"[Cache] Loading compiler cache for {ckpt_path}")
        artifact_bytes = artifact_path.read_bytes()
        torch.compiler.load_cache_artifacts(artifact_bytes)
    else:
        # only speed up weave_speed_forward
        optimized_forward = torch.compile(
            getattr(model, "weave_speed_forward"),
        )
        setattr(model, "weave_speed_forward", optimized_forward)


def load_flow_model(ckpt_path: str, name: str, device: str | torch.device = "cuda", hf_download: bool = True):
    # Loading Flux
    print("Init model")
    # ckpt_path = configs[name].ckpt_path
    # if (
    #     ckpt_path is None
    #     and configs[name].repo_id is not None
    #     and configs[name].repo_flow is not None
    #     and hf_download
    # ):
    #     ckpt_path = hf_hub_download(configs[name].repo_id, configs[name].repo_flow)
    
    # Completely clear old model memory
    gc.collect()
    torch.cuda.empty_cache()
    
    with torch.device("meta" if ckpt_path is not None else device):
        model = Flux(configs[name].params).to(torch.bfloat16)

    if ckpt_path is not None:
        print("Loading checkpoint")
        # load_sft doesn't support torch.device directly
        # First load to CPU to avoid GPU memory spikes
        sd = load_sft(ckpt_path, device="cpu")
        # sd = load_sft(ckpt_path, device=str(device))
        missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)
        print_load_warning(missing, unexpected)
        # Then move to target device
        model = model.to(device)
    
    # Second memory cleanup to avoid crash during trace
    gc.collect()
    torch.cuda.empty_cache()
    
    # TODO: torch_compile
    torch_compile(model, ckpt_path)
    return model

inference.py inference in every process but save in main process like device 0

   ....  get task parameters  from input queue to swith model

   pipeline.load_flow_model(dit_ckpt_path)

   try:
            result = pipeline(prompt=prompt,
                              width=width,
                              height=height,
                              .....
                              fast_forward=fast_forward,
                              residual_diff_threshold=residual_diff_threshold,
                              )
            
            output_queue.put((seed, result))
            # TODO: torch_compile
            if is_main:
                # save in main process
                util.save_cache_artifacts(ckpt_path=dit_ckpt_path)

model.py

class Flux(nn.Module):

    def forward(
            self,
            img: Tensor,
......
            fast_forward: bool = True,
            residual_diff_threshold=0.10,
    ) -> Tensor:
        if fast_forward:
            return self.weave_speed_forward(img,........
                                            residual_diff_threshold=residual_diff_threshold)

time record for inference in second : after few times/ switch from another model

origin torch.compile compile cache (switch from Model A to B when B has cached before)
B_pipeline 144/159 121/ 153 141/147

I don't know why the third situation not the same as the second (torch.compile(the seconded time)) even slower just use compile without any cache

Versions

Collecting environment information...
PyTorch version: 2.7.0+cu126
Is debug build: False
CUDA used to build PyTorch: 12.6
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.31

Python version: 3.10.11 (main, Apr 20 2023, 19:02:41) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-117-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA L20
GPU 1: NVIDIA L20
GPU 2: NVIDIA L20
GPU 3: NVIDIA L20
GPU 4: NVIDIA L20
GPU 5: NVIDIA L20
GPU 6: NVIDIA L20
GPU 7: NVIDIA L20

Nvidia driver version: 560.35.05
cuDNN version: Could not collect
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
Address sizes: 52 bits physical, 57 bits virtual
CPU(s): 128
On-line CPU(s) list: 0-127
Thread(s) per core: 2
Core(s) per socket: 32
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 143
Model name: Intel(R) Xeon(R) Gold 6462C
Stepping: 8
CPU MHz: 3300.000
CPU max MHz: 3900.0000
CPU min MHz: 800.0000
BogoMIPS: 6600.00
Virtualization: VT-x
L1d cache: 3 MiB
L1i cache: 2 MiB
L2 cache: 128 MiB
L3 cache: 120 MiB
NUMA node0 CPU(s): 0-31,64-95
NUMA node1 CPU(s): 32-63,96-127
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] efficientnet-pytorch==0.7.1
[pip3] mkl-fft==1.3.6
[pip3] mkl-random==1.2.2
[pip3] mkl-service==2.4.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.3
[pip3] nvidia-cublas-cu12==12.6.4.1
[pip3] nvidia-cuda-cupti-cu12==12.6.80
[pip3] nvidia-cuda-nvrtc-cu12==12.6.77
[pip3] nvidia-cuda-runtime-cu12==12.6.77
[pip3] nvidia-cudnn-cu12==9.5.1.17
[pip3] nvidia-cufft-cu12==11.3.0.4
[pip3] nvidia-curand-cu12==10.3.7.77
[pip3] nvidia-cusolver-cu12==11.7.1.2
[pip3] nvidia-cusparse-cu12==12.5.4.2
[pip3] nvidia-cusparselt-cu12==0.6.3
[pip3] nvidia-nccl-cu12==2.26.2
[pip3] nvidia-nvjitlink-cu12==12.6.85
[pip3] nvidia-nvtx-cu12==12.6.77
[pip3] onnx==1.14.1
[pip3] onnxruntime==1.15.1
[pip3] open-clip-torch==2.20.0
[pip3] pytorch-lightning==1.9.4
[pip3] pytorch-metric-learning==2.3.0
[pip3] torch==2.7.0
[pip3] torchaudio==2.7.0
[pip3] torchdiffeq==0.2.3
[pip3] torchelastic==0.2.2
[pip3] torchmetrics==1.0.3
[pip3] torchsde==0.2.5
[pip3] torchtext==0.6.0
[pip3] torchvision==0.22.0
[pip3] triton==3.3.0
[conda] blas 1.0 mkl
[conda] cuda-cudart 11.8.89 0 nvidia
[conda] cuda-cupti 11.8.87 0 nvidia
[conda] cuda-libraries 11.8.0 0 nvidia
[conda] cuda-nvrtc 11.8.89 0 nvidia
[conda] cuda-nvtx 11.8.86 0 nvidia
[conda] cuda-runtime 11.8.0 0 nvidia
[conda] efficientnet-pytorch 0.7.1 pypi_0 pypi
[conda] ffmpeg 4.3 hf484d3e_0 pytorch
[conda] intel-openmp 2023.1.0 hdb19cb5_46305
[conda] libcublas 11.11.3.6 0 nvidia
[conda] libcufft 10.9.0.58 0 nvidia
[conda] libcurand 10.3.2.106 0 nvidia
[conda] libcusolver 11.4.1.48 0 nvidia
[conda] libcusparse 11.7.5.86 0 nvidia
[conda] libjpeg-turbo 2.0.0 h9bf148f_0 pytorch
[conda] mkl 2023.1.0 h6d00ec8_46342
[conda] mkl-service 2.4.0 py310h5eee18b_1
[conda] mkl_fft 1.3.6 py310h1128e8f_1
[conda] mkl_random 1.2.2 py310h1128e8f_1
[conda] numpy 1.24.3 py310h5f9d8c6_1
[conda] numpy-base 1.24.3 py310hb5e798b_1
[conda] nvidia-cublas-cu12 12.6.4.1 pypi_0 pypi
[conda] nvidia-cuda-cupti-cu12 12.6.80 pypi_0 pypi
[conda] nvidia-cuda-nvrtc-cu12 12.6.77 pypi_0 pypi
[conda] nvidia-cuda-runtime-cu12 12.6.77 pypi_0 pypi
[conda] nvidia-cudnn-cu12 9.5.1.17 pypi_0 pypi
[conda] nvidia-cufft-cu12 11.3.0.4 pypi_0 pypi
[conda] nvidia-curand-cu12 10.3.7.77 pypi_0 pypi
[conda] nvidia-cusolver-cu12 11.7.1.2 pypi_0 pypi
[conda] nvidia-cusparse-cu12 12.5.4.2 pypi_0 pypi
[conda] nvidia-cusparselt-cu12 0.6.3 pypi_0 pypi
[conda] nvidia-nccl-cu12 2.26.2 pypi_0 pypi
[conda] nvidia-nvjitlink-cu12 12.6.85 pypi_0 pypi
[conda] nvidia-nvtx-cu12 12.6.77 pypi_0 pypi
[conda] open-clip-torch 2.20.0 pypi_0 pypi
[conda] pytorch-cuda 11.8 h7e8668a_5 pytorch
[conda] pytorch-lightning 1.9.4 pypi_0 pypi
[conda] pytorch-metric-learning 2.3.0 pypi_0 pypi
[conda] pytorch-mutex 1.0 cuda pytorch
[conda] tbb 2021.8.0 hdb19cb5_0
[conda] torch 2.7.0 pypi_0 pypi
[conda] torchaudio 2.7.0 pypi_0 pypi
[conda] torchdiffeq 0.2.3 pypi_0 pypi
[conda] torchelastic 0.2.2 pypi_0 pypi
[conda] torchmetrics 1.0.3 pypi_0 pypi
[conda] torchsde 0.2.5 pypi_0 pypi
[conda] torchtext 0.6.0 py_1 pytorch
[conda] torchvision 0.22.0 pypi_0 pypi
[conda] triton 3.3.0 pypi_0 pypi

cc @chauhang @penguinwu @oulgen @jamesjwu @masnesral

Metadata

Metadata

Assignees

No one assigned

    Labels

    compile-cacheoncall: pt2triagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions