Repository: open-compass/opencompass
Issue: [Bug] 试图添加mlc后端遇到问题，找不到cuda
Root cause: Validation Gap

### Prerequisite

- [X] I have searched [Issues](https://github.com/open-compass/opencompass/issues/) and [Discussions](https://github.com/open-compass/opencompass/discussions) but cannot get the expected help.
- [X] The bug has not been fixed in the [latest version](https://github.com/open-compass/opencompass).

### Type

I have modified the code (config is not considered code), or I'm working on my own tasks/models/datasets.

### Environment

`(mlc-chat-venv) zjlab@zjlab-MS-7B17:~/mlc-llm$ python -c "import opencompass.utils;import pprint;pprint.pprint(dict(opencompass.utils.collect_env()))"
{'CUDA available': True,
 'CUDA_HOME': '/usr/local/cuda-12.2',
 'GCC': 'gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0',
 'GPU 0': 'NVIDIA GeForce RTX 3080',
 'MMEngine': '0.10.4',
 'MUSA available': False,
 'NVCC': 'Cuda compilation tools, release 12.2, V12.2.91',
 'OpenCV': '4.10.0',
 'PyTorch': '2.3.1+cu121',
 'PyTorch compiling details': 'PyTorch built with:\n'
                              '  - GCC 9.3\n'
                              '  - C++ Version: 201703\n'
                              '  - Intel(R) oneAPI Math Kernel Library Version '
                              '2022.2-Product Build 20220804 for Intel(R) 64 '
                              'architecture applications\n'
                              '  - Intel(R) MKL-DNN v3.3.6 (Git Hash '
                              '86e6af5974177e513fd3fee58425e1063e7f1361)\n'
                              '  - OpenMP 201511 (a.k.a. OpenMP 4.5)\n'
                              '  - LAPACK is enabled (usually provided by '
                              'MKL)\n'
                              '  - NNPACK is enabled\n'
                              '  - CPU capability usage: AVX2\n'
                              '  - CUDA Runtime 12.1\n'
                              '  - NVCC architecture flags: '
                              '-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90\n'
                              '  - CuDNN 8.9.2\n'
                              '  - Magma 2.6.1\n'
                              '  - Build settings: BLAS_INFO=mkl, '
                              'BUILD_TYPE=Release, CUDA_VERSION=12.1, '
                              'CUDNN_VERSION=8.9.2, '
                              'CXX_COMPILER=/opt/rh/devtoolset-9/root/usr/bin/c++, '
                              'CXX_FLAGS= -D_GLIBCXX_USE_CXX11_ABI=0 '
                              '-fabi-version=11 -fvisibility-inlines-hidden '
                              '-DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO '
                              '-DLIBKINETO_NOROCTRACER -DUSE_FBGEMM '
                              '-DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK '
                              '-DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE '
                              '-O2 -fPIC -Wall -Wextra -Werror=return-type '
                              '-Werror=non-virtual-dtor -Werror=bool-operation '
                              '-Wnarrowing -Wno-missing-field-initializers '
                              '-Wno-type-limits -Wno-array-bounds '
                              '-Wno-unknown-pragmas -Wno-unused-parameter '
                              '-Wno-unused-function -Wno-unused-result '
                              '-Wno-strict-overflow -Wno-strict-aliasing '
                              '-Wno-stringop-overflow -Wsuggest-override '
                              '-Wno-psabi -Wno-error=pedantic '
                              '-Wno-error=old-style-cast -Wno-missing-braces '
                              '-fdiagnostics-color=always -faligned-new '
                              '-Wno-unused-but-set-variable '
                              '-Wno-maybe-uninitialized -fno-math-errno '
                              '-fno-trapping-math -Werror=format '
                              '-Wno-stringop-overflow, LAPACK_INFO=mkl, '
                              'PERF_WITH_AVX=1, PERF_WITH_AVX2=1, '
                              'PERF_WITH_AVX512=1, TORCH_VERSION=2.3.1, '
                              'USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, '
                              'USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, '
                              'USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, '
                              'USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, '
                              'USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, '
                              'USE_ROCM_KERNEL_ASSERT=OFF, \n',
 'Python': '3.12.5 | packaged by conda-forge | (main, Aug  8 2024, 18:36:51) '
           '[GCC 12.4.0]',
 'TorchVision': '0.18.1+cu121',
 'lmdeploy': '0.6.0',
 'numpy_random_seed': 2147483648,
 'opencompass': '0.3.1+d2acb93',
 'sys.platform': 'linux',
 'transformers': '4.44.2'}`

### Reproduces the problem - code/configuration sample

参考以下教程https://opencompass.readthedocs.io/en/latest/advanced_guides/new_model.html
添加opencompass/models/mlc_llm.py如下
`from typing import Dict, List, Optional
from opencompass.models.base import BaseModel
from opencompass.utils import get_logger
from mlc_llm import MLCEngine
from mlc_llm.interface.chat import ChatState, ChatCompletionOverride

from openai import OpenAI
from math import exp
import numpy as np
from IPython.display import display, HTML
import os
import torch

class MLC_LLM(BaseModel):
    """Model Wrapper for MLC."""

    def __init__(self,
                 model_path: str,
                 max_seq_len: int = 2048,
                 query_per_second: int = 1,
                 retry: int = 2,
                 **kwargs):
        super().__init__(path=model_path, max_seq_len=max_seq_len, **kwargs)
        
        self.logger = get_logger()
        self.engine = MLCEngine(model_path)
        self.chat_state = ChatState(self.engine)
        self.chat_state.overrides = ChatCompletionOverride(max_tokens=512)  # Set max_tokens as needed

    def generate(self,
                 inputs: List[str],
                 max_out_len: int = 512,
                 temperature: float = 0.7) -> List[str]:
        """Generate results given a list of inputs."""
        responses = []
        for input_text in inputs:
            response = self.engine.chat.completions.create(
                messages=[{"role": "user", "content": input_text}],
                model=self.engine.model,
                stream=True,
                logprobs=True,
            )
            response_text = ''.join(choice.delta.content for choice in response.choices)
            responses.append(response_text)
        
        return responses

    def get_token_len(self, prompt: str) -> int:
        """Get lengths of the tokenized string."""
        tokens = self.engine.chat.tokenizer.encode(prompt)
        return len(tokens)

    def terminate(self):
        """Terminate the engine."""
        self.engine.terminate()`

### Reproduces the problem - command or script

python ../opencompass/run.py ../opencompass/configs/eval_mlc_llm.py -w ../opencompass/outputs/qwen/mlc-llm

### Reproduces the problem - error message

outputs/qwen/mlc-llm/20240921_212320/logs/infer/mlc-react/gsm8k-agent_8.out中输出内容如下
`09/21 21:23:29 - OpenCompass - INFO - Task [mlc-react/gsm8k-agent_8]
[2024-09-21 21:23:34] INFO auto_device.py:88: [91mNot found[0m device: cuda:0
[2024-09-21 21:23:37] INFO auto_device.py:88: [91mNot found[0m device: rocm:0
[2024-09-21 21:23:40] INFO auto_device.py:88: [91mNot found[0m device: metal:0
[2024-09-21 21:23:42] INFO auto_device.py:88: [91mNot found[0m device: vulkan:0
[2024-09-21 21:23:45] INFO auto_device.py:88: [91mNot found[0m device: opencl:0
[2024-09-21 21:23:45] INFO auto_device.py:33: [91mNot found[0m: No available device detected
Traceback (most recent call last):
  File "/home/zjlab/opencompass/opencompass/tasks/openicl_infer.py", line 161, in <module>
    inferencer.run()
  File "/home/zjlab/opencompass/opencompass/tasks/openicl_infer.py", line 73, in run
    self.model = build_model_from_cfg(model_cfg)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/zjlab/opencompass/opencompass/utils/build.py", line 25, in build_model_from_cfg
    return MODELS.build(model_cfg)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/zjlab/anaconda3/envs/mlc-chat-venv/lib/python3.12/site-packages/mmengine/registry/registry.py", line 570, in build
    return self.build_func(cfg, *args, **kwargs, registry=self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/zjlab/anaconda3/envs/mlc-chat-venv/lib/python3.12/site-packages/mmengine/registry/build_functions.py", line 121, in build_from_cfg
    obj = obj_cls(**args)  # type: ignore
          ^^^^^^^^^^^^^^^
  File "/home/zjlab/opencompass/opencompass/models/lagent.py", line 17, in __init__
    llm = REGISTRY.build(llm)
          ^^^^^^^^^^^^^^^^^^^
  File "/home/zjlab/anaconda3/envs/mlc-chat-venv/lib/python3.12/site-packages/mmengine/registry/registry.py", line 570, in build
    return self.build_func(cfg, *args, **kwargs, registry=self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/zjlab/anaconda3/envs/mlc-chat-venv/lib/python3.12/site-packages/mmengine/registry/build_functions.py", line 121, in build_from_cfg
    obj = obj_cls(**args)  # type: ignore
          ^^^^^^^^^^^^^^^
  File "/home/zjlab/opencompass/opencompass/models/mlc_llm.py", line 25, in __init__
    self.engine = MLCEngine(model_path)
                  ^^^^^^^^^^^^^^^^^^^^^
  File "/home/zjlab/mlc-llm/python/mlc_llm/serve/engine.py", line 1477, in __init__
    super().__init__(
  File "/home/zjlab/mlc-llm/python/mlc_llm/serve/engine_base.py", line 584, in __init__
    assert isinstance(device, Device)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError
Exception ignored in: <function MLCEngineBase.__del__ at 0x701f13f7bec0>
Traceback (most recent call last):
  File "/home/zjlab/mlc-llm/python/mlc_llm/serve/engine_base.py", line 653, in __del__
    self.terminate()
  File "/home/zjlab/mlc-llm/python/mlc_llm/serve/engine_base.py", line 660, in terminate
    self._ffi["exit_background_loop"]()
    ^^^^^^^^^
AttributeError: 'MLCEngine' object has no attribute '_ffi'
`
似乎是找不到cuda，但是在相同的虚拟环境中运行mlc测试文件能够正常运行

### Other information

运行nvidia-smi能找到cuda，并且能够使用lmdeploy部署，应该是添加mlc后端有问题