Repository: pytorch
Issue: Multiprocessing using Gunicorn causing CUDA Error 
Labels: module: multiprocessing,module: cuda,triaged

### 🐛 Describe the bug

Hello, I have been developing a FastAPI application where we can access a HuggingFace model and use it for text generation. On top of it, I'm launching the service with Gunicorn so that we can handle concurrent users.
My goal is to load the model only once to GPU and allow the works to share the same model concurrently.

To do this, I loaded the model and tokenizer outside of the FastAPI endpoint, I also clearly stated the use of the spawn method and the --preload flag.
However, I'm still running into the following error, does anyone have an idea about this? I tried almost all the solutions I found on internet.

RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method

I'm launching the app through the main entry point.

hardware
EC2 instance: g4dn.4xlarge
GPU: NVIDIA
GPU memory: 16GB

### **Code**
```
## imports

#model = AutoGPTQForCausalLM.from_quantized(quantized_model_dir, device="cuda:0")
# Get the tokenizer

class CustomGunicornApp(BaseApplication):
    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {key: value for key, value in self.options.items() if key in self.cfg.settings and value is not None}
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


app = FastAPI()
@app.post("/get_response")
async def get_response(data : Dict[Any, Any]):

    system_prompt= data.get("system_prompt")
    user_input = data.get("user_input")
    
    try:
        prompt_template   = ....

        # create the chain
        chain = LLMChain(llm=llm, prompt=prompt_template,memory=memory)
        try:
            r = chain.run({"system_prompt": system_prompt, "input": user_input})
            print("reponse")
            print(r)
            return {"response": r}
            
        except Exception as e:
            import traceback
            traceback.print_exc()
            raise  
    except Exception as e:
        return {"response": e}


if __name__ == '__main__':
    torch.multiprocessing.set_start_method('spawn', force=True)

    use_triton = False
    memory = ConversationBufferWindowMemory(k=20, memory_key="history",input_key="input")
    model_id = "TheBloke/Llama-2-13B-chat-GPTQ"
    model_basename = "model"
    tokenizer = AutoTokenizer.from_pretrained(model_id, is_split_into_words=True)
    model = AutoGPTQForCausalLM.from_quantized(model_id,
            model_basename=model_basename,
            use_safetensors=True,
            trust_remote_code=True,
            device="cuda:0",
            use_triton=use_triton,
            quantize_config=None)
    
    pipe = pipeline(
        "text-generation",
        model=model,
        tokenizer=tokenizer,
        max_new_tokens=128,
        temperature=0.7,
        top_p=0.95,
        repetition_penalty=1.15
    )
    llm=HuggingFacePipeline(pipeline=pipe)
    # Specify the number of Gunicorn worker processes
    gunicorn_options = {
        'bind': '0.0.0.0:8000',
        'workers': 2,
        'worker_class': 'uvicorn.workers.UvicornWorker',
        'preload_app': True,
        'timeout': 120,
        'log-level': 'info',
        'access-logfile': '-',
    }

    CustomGunicornApp(app, options=gunicorn_options).run()
```

### **Error Trace**
[2023-12-29 19:49:21 +0000] [1930] [ERROR] Exception in ASGI application
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 408, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "/home/ubuntu/.local/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
    return await self.app(scope, receive, send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/fastapi/applications.py", line 1106, in __call__
    await super().__call__(scope, receive, send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/applications.py", line 122, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__
    raise exc
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
    raise exc
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__
    raise e
  File "/home/ubuntu/.local/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__
    await self.app(scope, receive, send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/starlette/routing.py", line 66, in app
    response = await func(request)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/fastapi/routing.py", line 274, in app
    raw_response = await run_endpoint_function(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/fastapi/routing.py", line 191, in run_endpoint_function
    return await dependant.call(**values)
  File "/home/ubuntu/chatbot/backend/hf_enpoint.py", line 74, in get_response
    r = chain.run({"system_prompt": system_prompt, "input": user_input})
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain/chains/base.py", line 507, in run
    return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain/chains/base.py", line 312, in __call__
    raise e
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain/chains/base.py", line 306, in __call__
    self._call(inputs, run_manager=run_manager)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain/chains/llm.py", line 103, in _call
    response = self.generate([inputs], run_manager=run_manager)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain/chains/llm.py", line 115, in generate
    return self.llm.generate_prompt(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 516, in generate_prompt    
    return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 666, in generate
    output = self._generate_helper(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 553, in _generate_helper   
    raise e
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 540, in _generate_helper   
    self._generate(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/langchain_community/llms/huggingface_pipeline.py", line 203, in _generate    responses = self.pipeline(batch_prompts)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/pipelines/text_generation.py", line 204, in __call__        
    return super().__call__(text_inputs, **kwargs)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/pipelines/base.py", line 1110, in __call__
    outputs = list(final_iterator)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/pipelines/pt_utils.py", line 124, in __next__
    item = next(self.iterator)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/pipelines/pt_utils.py", line 125, in __next__
    processed = self.infer(item, **self.params)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/pipelines/base.py", line 1027, in forward
    with self.device_placement():
  File "/usr/lib/python3.10/contextlib.py", line 135, in __enter__
    return next(self.gen)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/pipelines/base.py", line 912, in device_placement
    with torch.cuda.device(self.device):
  File "/usr/local/lib/python3.10/dist-packages/torch/cuda/__init__.py", line 370, in __enter__
    self.prev_idx = torch.cuda._exchange_device(self.idx)
  File "/usr/local/lib/python3.10/dist-packages/torch/cuda/__init__.py", line 284, in _lazy_init
    raise RuntimeError(
RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method

### Versions

Collecting environment information...
PyTorch version: 2.1.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.2.0-1017-aws-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.1.66
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Tesla T4
Nvidia driver version: 530.30.02
cuDNN version: Could not collect
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             16
On-line CPU(s) list:                0-15
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 2
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           7
BogoMIPS:                           5000.01
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt 
clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke avx512_vnni
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          256 KiB (8 instances)
L1i cache:                          256 KiB (8 instances)
L2 cache:                           8 MiB (8 instances)
L3 cache:                           35.8 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-15
Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:        KVM: Mitigation: VMX unsupported
Vulnerability L1tf:                 Mitigation; PTE Inversion
Vulnerability Mds:                  Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:             Mitigation; PTI
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:             Vulnerable
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Vulnerable
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.2
[pip3] torch==2.1.1
[pip3] torchaudio==2.1.1
[pip3] torchdata==0.7.1
[pip3] torchtext==0.16.2
[pip3] torchvision==0.16.1
[pip3] triton==2.1.0

cc @VitalyFedyunin @ptrblck