Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Random Segmentation Faults During OneDiff (OneFlow) Inference in Multi-threaded Python Program #1080

Open
yingchingl opened this issue Aug 13, 2024 · 9 comments
Labels
Request-bug Something isn't working

Comments

@yingchingl
Copy link

Your current environment information

Collecting environment information...
PyTorch version: 2.1.1+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OneFlow version: path: ['/opt/conda/lib/python3.10/site-packages/oneflow'], version: 0.9.1.dev20240515+cu118, git_commit: ec7b682, cmake_build_type: Release, rdma: True, mlir: True, enterprise: False
Nexfort version: none
OneDiff version: 1.2.0.dev202407160130
OneDiffX version: 1.2.0.dev1

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.28.1
Libc version: glibc-2.31

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-97-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 GeForce RTX 3090
Nvidia driver version: 535.161.07
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.0
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: 46 bits physical, 57 bits virtual
CPU(s): 112
On-line CPU(s) list: 0-111
Thread(s) per core: 2
Core(s) per socket: 28
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 106
Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz
Stepping: 6
CPU MHz: 800.000
CPU max MHz: 3100.0000
CPU min MHz: 800.0000
BogoMIPS: 4000.00
Virtualization: VT-x
L1d cache: 2.6 MiB
L1i cache: 1.8 MiB
L2 cache: 70 MiB
L3 cache: 84 MiB
NUMA node0 CPU(s): 0-27,56-83
NUMA node1 CPU(s): 28-55,84-111
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
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 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 invpcid_single intel_ppin 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 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] diffusers==0.21.0
[pip3] numpy==1.26.0
[pip3] onnx==1.15.0
[pip3] onnxruntime-gpu==1.17.0
[pip3] torch==2.1.1+cu118
[pip3] torchaudio==2.1.1+cu118
[pip3] torchelastic==0.2.2
[pip3] torchsde==0.2.6
[pip3] torchvision==0.16.1+cu118
[pip3] transformers==4.35.2
[pip3] triton==2.1.0
[conda] blas 1.0 mkl
[conda] ffmpeg 4.3 hf484d3e_0 pytorch
[conda] libjpeg-turbo 2.0.0 h9bf148f_0 pytorch
[conda] mkl 2023.1.0 h213fc3f_46343
[conda] mkl-service 2.4.0 py310h5eee18b_1
[conda] mkl_fft 1.3.8 py310h5eee18b_0
[conda] mkl_random 1.2.4 py310hdb19cb5_0
[conda] numpy 1.26.0 py310h5f9d8c6_0
[conda] numpy-base 1.26.0 py310hb5e798b_0
[conda] pytorch-cuda 11.8 h7e8668a_5 pytorch
[conda] pytorch-mutex 1.0 cuda pytorch
[conda] torch 2.1.1+cu118 pypi_0 pypi
[conda] torchaudio 2.1.1+cu118 pypi_0 pypi
[conda] torchelastic 0.2.2 pypi_0 pypi
[conda] torchsde 0.2.6 pypi_0 pypi
[conda] torchtriton 2.1.0 py310 pytorch
[conda] torchvision 0.16.1+cu118 pypi_0 pypi

🐛 Describe the bug

I'm experiencing random segmentation faults when using OneDiff to accelerate SDXL inference in a multi-threaded Python environment. The issue appears to be related to memory allocation and deallocation without properly handling the Python Global Interpreter Lock (GIL).

When the issue occurs, the command window outputs one of the following messages:

Stack trace (most recent call last) in thread 31:
   Object "/opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so", at 0x7f22c10d3962, in functional::from_dlpack(_object*, *object*, *object*)
   Object "/opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so", at 0x7f22c0fcc6ed, in 
   Object "/opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so", at 0x7f22c118bf64, in PyTensor_New(std::shared_ptr<Tensor> const&)
Segmentation fault (Address not mapped to object [0x1])
Segmentation fault (Address not mapped to object [0x2])

Since there isn't much information, I used GDB to debug and captured the following stack trace when the segmentation fault occurs:

#0  0x00000000004d6b65 in pymalloc_alloc (ctx=0x0, nbytes=32) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:1961
#1  _PyObject_Malloc (nbytes=32, ctx=0x0) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:1961
#2  PyObject_Malloc (size=32) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:685
#3  0x00000000004deb00 in PyType_GenericAlloc (type=0x780fc80eff30, nitems=0) at /usr/local/src/conda/python-3.10.13/Objects/typeobject.c:1159
#4  0x0000781117628945 in oneflow::one::PyTensor_New(std::shared_ptr<oneflow::one::Tensor> const&) () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#5  0x0000781117444cbe in ?? () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#6  0x000078111756aae3 in oneflow::one::functional::from_dlpack(_object*, _object*, _object*) () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#7  0x00000000004fc697 in cfunction_call (func=<built-in method from_dlpack of module object at remote 0x7811215629d0>, args=<optimized out>, kwargs=<optimized out>) at /usr/local/src/conda/python-3.10.13/Objects/methodobject.c:543
#8  0x00000000004f614b in _PyObject_MakeTpCall (tstate=0x6b1eee0, callable=<built-in method from_dlpack of module object at remote 0x7811215629d0>, args=<optimized out>, nargs=<optimized out>, keywords=0x0) at /usr/local/src/conda/python-3.10.13/Objects/call.c:224
#9  0x00000000004f2376 in _PyObject_VectorcallTstate (kwnames=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>, nargsf=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>, args=0x780ef056a3c0, callable=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>, tstate=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Include/cpython/abstract.h:112
#10 _PyObject_VectorcallTstate (kwnames=0x0, nargsf=<optimized out>, args=0x780ef056a3c0, callable=<built-in method from_dlpack of module object at remote 0x7811215629d0>, tstate=<optimized out>) at /usr/local/src/conda/python-3.10.13/Include/cpython/abstract.h:99
#11 PyObject_Vectorcall (kwnames=0x0, nargsf=<optimized out>, args=0x780ef056a3c0, callable=<built-in method from_dlpack of module object at remote 0x7811215629d0>) at /usr/local/src/conda/python-3.10.13/Include/cpython/abstract.h:123
#12 call_function (kwnames=0x0, oparg=<optimized out>, pp_stack=<synthetic pointer>, trace_info=0x7804ff4d8850, tstate=<optimized out>) at /usr/local/src/conda/python-3.10.13/Python/ceval.c:5893
#13 _PyEval_EvalFrameDefault (tstate=<optimized out>, f=Frame 0x780ef056a240, for file /opt/conda/lib/python3.10/site-packages/oneflow/utils/tensor/from_or_to_torch_tensor.py, line 65, in from_torch (torch_tensor=<Tensor at remote 0x780ba07b84f0>, torch=<module at remote 0x7812c97500e0>), throwflag=<optimized out>) at /usr/local/src/conda/python-3.10.13/Python/ceval.c:4181

The program consistently crashes in the pymalloc_alloc function, trying to access an invalid memory address.
I suspect the issue may be related to the handling of the Python Global Interpreter Lock (GIL) during memory allocation and deallocation processes.
To verify this hypothesis, I've created a test program (sdxl_onediff_test.py) based on the examples of Diffusers and OneDiffX that simulates using OneFlow for accelerated inference while another thread performs Python memory allocation and deallocation:

# sdxl_onediff_test.py
import os
import cv2
import time
import torch
import random
import argparse
import threading
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
from onediffx import compile_pipe, save_pipe, load_pipe

# download images
image_t2i = load_image(
    "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
)

pipe_t2i = None


class TestMemAlloc:
    def __init__(self):
        pass

    def allocate_and_free_small_mem(self):
        dic = dict()
        for k in range(65536):
            s = random.randint(2, 256)
            dic[k] = bytearray(s)
        del dic


def run_t2i(compile_and_save=False):
    global pipe_t2i
    # initialize the models and pipeline
    if pipe_t2i is None:
        controlnet = ControlNetModel.from_pretrained(
            "diffusers/controlnet-canny-sdxl-1.0",
            torch_dtype=torch.float16
        )
        vae = AutoencoderKL.from_pretrained(
            "madebyollin/sdxl-vae-fp16-fix",
            torch_dtype=torch.float16
        )
        pipe_t2i = StableDiffusionXLControlNetPipeline.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0",
            controlnet=controlnet,
            vae=vae,
            torch_dtype=torch.float16
        ).to('cuda')

        pipe_t2i = compile_pipe(pipe_t2i)
        if not compile_and_save:
            load_pipe(pipe_t2i, dir="cached_t2i_pipe")

    controlnet_conditioning_scale = 0.5  # recommended for good generalization
    prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
    negative_prompt = "low quality, bad quality, sketches"
    # get canny image
    image = np.array(image_t2i)
    image = cv2.Canny(image, 100, 200)
    image = image[:, :, None]
    image = np.concatenate([image, image, image], axis=2)
    canny_image = Image.fromarray(image)

    # generate image
    image = pipe_t2i(
        prompt,
        controlnet_conditioning_scale=controlnet_conditioning_scale,
        image=canny_image,
        num_inference_steps=8,
    ).images[0]

    if compile_and_save:
        save_pipe(pipe_t2i, dir="cached_t2i_pipe")

    return image


def test_mem_alloc():
    t = threading.current_thread()
    while not getattr(t, "stop_thread", False):
        time.sleep(0.1)
        test_ma = TestMemAlloc()
        test_ma.allocate_and_free_small_mem()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--compile_and_save", action="store_true", default=False,
                        help="compile and save the compiled pipe.")
    input_args = parser.parse_args()

    thread_pool = []
    if not input_args.compile_and_save:
        for num in range(1):
            t = threading.Thread(target=test_mem_alloc)
            t.start()
            thread_pool.append(t)

    out_dir = "./outputs"
    os.makedirs(out_dir, exist_ok=True)
    total_rounds = 10000
    for i in range(total_rounds):
        out_t2i = run_t2i(input_args.compile_and_save)

        if input_args.compile_and_save:
            break

        out_t2i.save(os.path.join(out_dir, f"t2i_{i}.jpg"))
        print(f"onediff test - {i+1}/{total_rounds}...")

    for t in thread_pool:
        t.stop_thread = True

To reproduce:

  1. Run python sdxl_onediff_test.py --compile_and_save to compile and save the compiled pipe.
  2. Run python sdxl_onediff_test.py to start the test.

The segmentation fault typically occurs within a few seconds to minutes.

@yingchingl yingchingl added the Request-bug Something isn't working label Aug 13, 2024
@yingchingl
Copy link
Author

Additional Debugging

When running the test program with PYTHONMALLOC=debug environment variable, Python will check the status of the GIL when performing memory allocation and deallocation:

PYTHONMALLOC=debug python sdxl_onediff_test.py

The captured stack trace is as follows:

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x000072fcf0ac7859 in __GI_abort () at abort.c:79
#2  0x00000000004a6ef3 in fatal_error_exit (status=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Python/pylifecycle.c:2556
#3  fatal_error (fd=<optimized out>, header=header@entry=1, prefix=prefix@entry=0x6b6a90 <__func__.5.lto_priv.0> "_PyMem_DebugFree", msg=msg@entry=0x627e68 "Python memory allocator called without holding the GIL", status=status@entry=-1) at /usr/local/src/conda/python-3.10.13/Python/pylifecycle.c:2667
#4  0x00000000004a727d in _Py_FatalErrorFunc (func=func@entry=0x6b6a90 <__func__.5.lto_priv.0> "_PyMem_DebugFree", msg=msg@entry=0x627e68 "Python memory allocator called without holding the GIL") at /usr/local/src/conda/python-3.10.13/Python/pylifecycle.c:2753
#5  0x0000000000423122 in _PyMem_DebugCheckGIL (func=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:2646
#6  0x00000000004dd024 in _PyMem_DebugFree (ctx=0x743040 <_PyMem_Debug+96>, ptr=0x72f37c77f4c0) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:2670
#7  0x000072f57c11946c in ?? () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#8  0x000072f45e27ec0d in std::_Sp_counted_ptr_inplace<oneflow::one::LocalTensor, std::allocator<oneflow::one::LocalTensor>, (__gnu_cxx::_Lock_policy)2>::_M_dispose() () from /opt/conda/lib/python3.10/site-packages/oneflow/../oneflow.libs/liboneflow-d0782696.so
#9  0x000072f57c097a1a in oneflow::deleter(DLManagedTensor*) () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#10 0x000072fc54ddb28c in c10::deleteInefficientStdFunctionContext(void*) () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#11 0x000072fcbf9bb7b6 in c10::StorageImpl::~StorageImpl() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libtorch_python.so
#12 0x000072fc54e02ca7 in c10::intrusive_ptr<c10::StorageImpl, c10::detail::intrusive_target_default_null_type<c10::StorageImpl> >::reset_() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#13 0x000072fc54dfacb3 in c10::TensorImpl::~TensorImpl() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#14 0x000072fc54dfae49 in c10::TensorImpl::~TensorImpl() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#15 0x000072fcbfc6b738 in THPVariable_clear(THPVariable*) () from /opt/conda/lib/python3.10/site-packages/torch/lib/libtorch_python.so
#16 0x000072fcbfc6bac5 in THPVariable_subclass_dealloc(_object*) () from /opt/conda/lib/python3.10/site-packages/torch/lib/libtorch_python.so
#17 0x00000000004dd8e4 in _Py_Dealloc (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Objects/object.c:2295
#18 _Py_DECREF (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Include/object.h:500
#19 _Py_XDECREF (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Include/object.h:567
#20 list_dealloc (op=0x72f37c78b200) at /usr/local/src/conda/python-3.10.13/Objects/listobject.c:355
#21 0x00000000004f1820 in _Py_Dealloc (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Objects/object.c:2295
#22 _Py_DECREF (op=<optimized out>) at /usr/local/src/conda/python-3.10.13/Include/object.h:500
#23 _Py_XDECREF (op=<optimized out>) at /usr/local/src/conda/python-3.10.13/Include/object.h:567
#24 _PyEval_EvalFrameDefault (tstate=<optimized out>, f=Frame 0x6c043530, for file /opt/conda/lib/python3.10/site-packages/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py, line 1100, in __call__ (self=<StableDiffusionXLControlNetPipeline(_internal_dict=<FrozenDict(vae=('diffusers', 'AutoencoderKL'), text_encoder=('onediff', 'MixedOneflowDeployableModule'), text_encoder_2=('onediff', 'MixedOneflowDeployableModule'), tokenizer=('transformers', 'CLIPTokenizer'), tokenizer_2=('transformers', 'CLIPTokenizer'), unet=('onediff', 'MixedOneflowDeployableModule'), controlnet=('onediff', 'MixedOneflowDeployableModule'), scheduler=('diffusers', 'EulerDiscreteScheduler'), force_zeros_for_empty_prompt=True, _name_or_path='stabilityai/stable-diffusion-xl-base-1.0', _FrozenDict__frozen=True) at remote 0x72f8b83427b0>, vae=<AutoencoderKL(_internal_dict=<FrozenDict(in_channels=3, out_channels=3, down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D'], up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBloc...(truncated), throwflag=<optimized out>) at /usr/local/src/conda/python-3.10.13/Python/ceval.c:1882

This reveals that the Python memory allocator is being called without holding the GIL.

@bigmover
Copy link

bigmover commented Sep 9, 2024

Additional Debugging

When running the test program with PYTHONMALLOC=debug environment variable, Python will check the status of the GIL when performing memory allocation and deallocation:

PYTHONMALLOC=debug python sdxl_onediff_test.py

The captured stack trace is as follows:

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x000072fcf0ac7859 in __GI_abort () at abort.c:79
#2  0x00000000004a6ef3 in fatal_error_exit (status=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Python/pylifecycle.c:2556
#3  fatal_error (fd=<optimized out>, header=header@entry=1, prefix=prefix@entry=0x6b6a90 <__func__.5.lto_priv.0> "_PyMem_DebugFree", msg=msg@entry=0x627e68 "Python memory allocator called without holding the GIL", status=status@entry=-1) at /usr/local/src/conda/python-3.10.13/Python/pylifecycle.c:2667
#4  0x00000000004a727d in _Py_FatalErrorFunc (func=func@entry=0x6b6a90 <__func__.5.lto_priv.0> "_PyMem_DebugFree", msg=msg@entry=0x627e68 "Python memory allocator called without holding the GIL") at /usr/local/src/conda/python-3.10.13/Python/pylifecycle.c:2753
#5  0x0000000000423122 in _PyMem_DebugCheckGIL (func=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:2646
#6  0x00000000004dd024 in _PyMem_DebugFree (ctx=0x743040 <_PyMem_Debug+96>, ptr=0x72f37c77f4c0) at /usr/local/src/conda/python-3.10.13/Objects/obmalloc.c:2670
#7  0x000072f57c11946c in ?? () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#8  0x000072f45e27ec0d in std::_Sp_counted_ptr_inplace<oneflow::one::LocalTensor, std::allocator<oneflow::one::LocalTensor>, (__gnu_cxx::_Lock_policy)2>::_M_dispose() () from /opt/conda/lib/python3.10/site-packages/oneflow/../oneflow.libs/liboneflow-d0782696.so
#9  0x000072f57c097a1a in oneflow::deleter(DLManagedTensor*) () from /opt/conda/lib/python3.10/site-packages/oneflow/_oneflow_internal.cpython-310-x86_64-linux-gnu.so
#10 0x000072fc54ddb28c in c10::deleteInefficientStdFunctionContext(void*) () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#11 0x000072fcbf9bb7b6 in c10::StorageImpl::~StorageImpl() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libtorch_python.so
#12 0x000072fc54e02ca7 in c10::intrusive_ptr<c10::StorageImpl, c10::detail::intrusive_target_default_null_type<c10::StorageImpl> >::reset_() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#13 0x000072fc54dfacb3 in c10::TensorImpl::~TensorImpl() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#14 0x000072fc54dfae49 in c10::TensorImpl::~TensorImpl() () from /opt/conda/lib/python3.10/site-packages/torch/lib/libc10.so
#15 0x000072fcbfc6b738 in THPVariable_clear(THPVariable*) () from /opt/conda/lib/python3.10/site-packages/torch/lib/libtorch_python.so
#16 0x000072fcbfc6bac5 in THPVariable_subclass_dealloc(_object*) () from /opt/conda/lib/python3.10/site-packages/torch/lib/libtorch_python.so
#17 0x00000000004dd8e4 in _Py_Dealloc (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Objects/object.c:2295
#18 _Py_DECREF (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Include/object.h:500
#19 _Py_XDECREF (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Include/object.h:567
#20 list_dealloc (op=0x72f37c78b200) at /usr/local/src/conda/python-3.10.13/Objects/listobject.c:355
#21 0x00000000004f1820 in _Py_Dealloc (op=<error reading variable: dwarf2_find_location_expression: Corrupted DWARF expression.>) at /usr/local/src/conda/python-3.10.13/Objects/object.c:2295
#22 _Py_DECREF (op=<optimized out>) at /usr/local/src/conda/python-3.10.13/Include/object.h:500
#23 _Py_XDECREF (op=<optimized out>) at /usr/local/src/conda/python-3.10.13/Include/object.h:567
#24 _PyEval_EvalFrameDefault (tstate=<optimized out>, f=Frame 0x6c043530, for file /opt/conda/lib/python3.10/site-packages/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py, line 1100, in __call__ (self=<StableDiffusionXLControlNetPipeline(_internal_dict=<FrozenDict(vae=('diffusers', 'AutoencoderKL'), text_encoder=('onediff', 'MixedOneflowDeployableModule'), text_encoder_2=('onediff', 'MixedOneflowDeployableModule'), tokenizer=('transformers', 'CLIPTokenizer'), tokenizer_2=('transformers', 'CLIPTokenizer'), unet=('onediff', 'MixedOneflowDeployableModule'), controlnet=('onediff', 'MixedOneflowDeployableModule'), scheduler=('diffusers', 'EulerDiscreteScheduler'), force_zeros_for_empty_prompt=True, _name_or_path='stabilityai/stable-diffusion-xl-base-1.0', _FrozenDict__frozen=True) at remote 0x72f8b83427b0>, vae=<AutoencoderKL(_internal_dict=<FrozenDict(in_channels=3, out_channels=3, down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D'], up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBloc...(truncated), throwflag=<optimized out>) at /usr/local/src/conda/python-3.10.13/Python/ceval.c:1882

This reveals that the Python memory allocator is being called without holding the GIL.

Hi @yingchingl Were you able to solve it? Would you mind kindly to give some advice about it?

@bigmover
Copy link

bigmover commented Sep 9, 2024

@strint Would you mind to give a loot at the issue ? Fatal Python error: _PyMem_DebugFree: Python memory allocator called without holding the GIL Deeply grateful!

Stack trace (most recent call last) in thread 16004:
   Object "/home/admin/miniconda3/lib/python3.9/site-packages/oneflow/_oneflow_internal.cpython-39-x86_64-linux-gnu.so", at 0x7fa7f3eec1d9, in deleter(DLManagedTensor*)
   Object "/home/admin/miniconda3/lib/python3.9/site-packages/oneflow/../oneflow.libs/liboneflow-6e5725f6.so", at 0x7fa6fd00b29c, in std::_Sp_counted_ptr_inplace<LocalTensor, std::allocator<LocalTensor>, (__gnu_cxx::_Lock_policy)2>::_M_dispose()
   Object "/home/admin/miniconda3/lib/python3.9/site-packages/oneflow/_oneflow_internal.cpython-39-x86_64-linux-gnu.so", at 0x7fa7f3f6e1eb, in

@hjchen2 Would you mind to give a look at the issue

@yingchingl
Copy link
Author

Hi @yingchingl Were you able to solve it? Would you mind kindly to give some advice about it?

Hi @bigmover ,
No, I can't solve it yet. Because the code of oneflow used by onediff is not public, I cannot debug into it and see where the problem occurs.

@strint
Copy link
Collaborator

strint commented Sep 20, 2024

Multi-threaded Python Program

Please don't try to use cuda/python/onediff with Multi-thread because it's usually blocked by the Python GIL or not thread-safe.

Using multi-process is recommended.

@bigmover
Copy link

Hi @yingchingl Were you able to solve it? Would you mind kindly to give some advice about it?

Hi @bigmover , No, I can't solve it yet. Because the code of oneflow used by onediff is not public, I cannot debug into it and see where the problem occurs.

GOT IT! Thank you!

@bigmover
Copy link

Multi-threaded Python Program

Please don't try to use cuda/python/onediff with Multi-thread because it's usually blocked by the Python GIL or not thread-safe.

Using multi-process is recommended.

@strint OK Thank you for your kindly reply! Onediff have flash attention ? It will use more GPU memory when using oneflow.compile?

@strint
Copy link
Collaborator

strint commented Oct 25, 2024

Multi-threaded Python Program

Please don't try to use cuda/python/onediff with Multi-thread because it's usually blocked by the Python GIL or not thread-safe.
Using multi-process is recommended.

@strint OK Thank you for your kindly reply! Onediff have flash attention ? It will use more GPU memory when using oneflow.compile?

Yes, we are using a customized flash attention.

Compileing UNet won't use more GPU memory, but compiling VAE does because VAE has a large output tensor. oneflow compile share model weight memory with torch but doesn't share output tensor memory with torch.

@niehen6174
Copy link

Hi @bigmover @yingchingl , I have the same problem, I want to ask if you have any solution or idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Request-bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants