Skip to content

Conversation

@devnoff
Copy link

@devnoff devnoff commented Apr 25, 2025

요약 (Summary)

이 PR은 Dia 모델을 macOS 환경 (Apple Silicon 및 Intel)에서 실행할 수 있도록 지원을 추가합니다. Apple Silicon의 Metal Performance Shaders (MPS)를 활용한 GPU 가속과 CPU 폴백(fallback) 실행을 모두 지원합니다.

동기 (Motivation)

기존 코드는 주로 CUDA 환경을 기준으로 테스트 및 설정되어 있어 macOS 사용자가 로컬 환경에서 모델을 사용하기 어려웠습니다. 이 변경을 통해 macOS 사용자, 특히 Apple Silicon 칩을 사용하는 사용자들이 모델을 더 쉽게 활용할 수 있게 됩니다.

변경 내용 (Changes Made)

  • Python 버전 요구사항: 테스트 결과, Python 3.13 환경에서 descript-audio-codec 라이브러리와의 호환성 문제가 발견되어 Python 3.10을 필수 요구사항으로 지정했습니다. (.python-version 파일은 있으나, pyenv 사용은 사용자의 선택사항입니다.)
  • 장치 처리 로직 수정:
    • app.py, cli.py, dia/model.py, dia/state.py 등 관련 파일에서 CUDA 외에 MPS (torch.backends.mps.is_available()) 및 CPU 장치를 감지하고 사용하도록 로직을 수정했습니다.
    • Gradio 앱 (app.py)과 CLI (cli.py)에서 --device mps 또는 --device cpu 인자를 통해 실행 장치를 명시적으로 선택할 수 있도록 지원합니다.
    • cli.py의 시드 설정 로직(set_seed)이 현재 활성화된 장치(CUDA, MPS, CPU)를 인식하도록 수정했습니다.
  • 모델 로딩 오류 수정:
    • Python 3.10 환경에서 모델 로딩 시 발생했던 다양한 오류들을 해결했습니다.
      • Pydantic 모델(DiaConfig, DataConfig 등) 초기화 및 config.json 파싱 관련 TypeErrorAttributeError 해결. (log6.txt 참고)
      • descript-audio-codec (DAC) 모델 로딩 방식 수정 (dac.DAC.load() 사용).
      • DiaModel 초기화 시 dtype 처리 방식 수정.
      • 내부 컴포넌트(DiaModel, Encoder, Decoder 등)에 올바른 설정 객체(DiaConfig)가 전달되도록 수정.
  • 문서 업데이트:
    • README.md 파일의 "Quickstart" 및 "Hardware and Inference Speed" 섹션을 업데이트하여 다음 내용을 추가/수정했습니다:
      • Python 3.10 요구사항 명시.
      • 표준 pipvenv를 사용한 권장 설치 방법 안내.
      • macOS 환경에서의 실행 방법 (MPS/CPU 장치 옵션).
      • 하드웨어 섹션에 macOS 지원 명시 및 성능 관련 참고사항 추가.
      • Triton 라이브러리는 macOS에서 지원되지 않음 명시.
  • 기타:
    • 디버깅 과정에서 추가했던 print 문들을 제거했습니다.

테스트 (Testing)

  • macOS (Apple Silicon, M-시리즈 칩) 환경에서 Python 3.10 가상 환경을 구성하여 테스트했습니다.
  • pip install . 명령어로 의존성 설치가 정상적으로 완료됨을 확인했습니다.
  • python3 cli.py "..." --output test_mps.wav --device mps 명령 실행 시, MPS 장치를 사용하여 오류 없이 오디오 파일이 성공적으로 생성 및 저장됨을 확인했습니다.
  • 이번 변경으로 인해 cuda 환경에서의 사이드이팩트 여부는 확인하지 못 했습니다.
  • CPU 장치를 사용할 경우 매우 느리지만 오디오 파일이 성공적으로 생성 및 저장됨을 확인했습니다.

참고 (Notes)

  • 이 PR은 Pydantic 모델 관련 문제를 해결하기 위해 여러 시도를 거쳤으나, 최종적으로는 원래의 Pydantic 모델 구조를 유지하면서 Python 3.10 환경에서 정상 동작하도록 수정했습니다. (임시로 딕셔너리를 사용했던 코드는 복구됨)
  • uv를 사용한 설치는 환경 설정 문제로 인해 불안정할 수 있어, 표준 pip 사용을 권장하는 방향으로 문서를 수정했습니다.
  • 작업의 전 과정은 Cursor with gemini-2.5-pro-exp-03-25 를 통해 진행되었습니다. python 및 모델 관련 지식이 전무하기 때문에 관련 질문에 답해드릴 수 없음을 미리 양해구합니다.

@maslovw
Copy link

maslovw commented Apr 26, 2025

Checked on

  Model Name: MacBook Pro
  Model Identifier: MacBookPro18,2
  Model Number: Z14V001TCD/A
  Chip: Apple M1 Max
  Total Number of Cores: 10 (8 performance and 2 efficiency)
  Memory: 64 GB
$ git clone [email protected]:nari-labs/dia.git
$ git remote add devnoff [email protected]:devnoff/dia.git
$ git fetch devnoff mac
$ git co devnoff/mac
$ python3.10 -m venv ~/venv/dia
$ source ~/venv/dia/bin/activate
$ pip install -e .
$ python --version
    Python 3.10.16
$ python app.py

Using device: mps
Loading Nari model...
config.json: 100%|███████████████████████████████████████████████████████| 941/941 [00:00<00:00, 1.27MB/s]
dia-v0_1.pth: 100%|██████████████████████████████████████████████████| 6.44G/6.44G [04:42<00:00, 22.8MB/s]
/Users/maslovw/venv/dia/lib/python3.10/site-packages/torch/nn/utils/weight_norm.py:143: FutureWarning: `torch.nn.utils.weight_norm` is deprecated in favor of `torch.nn.utils.parametrizations.weight_norm`.
  WeightNorm.apply(module, name, dim)
Launching Gradio interface...
* Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.
--- Inside _prepare_generation ---
Type of self.config: <class 'dia.config.DiaConfig'>
Content of self.config (or keys): dict_keys(['version', 'model', 'training', 'data'])
--- End Debug Print ---
Generation finished in 44.50 seconds.
Resampled audio from 387584 to 412323 samples for 0.94x speed.
Audio conversion successful. Final shape: (412323,), Sample Rate: 44100
Converted audio to int16 for Gradio output.

Generation of an example is successful

@galosa
Copy link

galosa commented Apr 27, 2025

works well on mac m3 pro

@iamsh4
Copy link

iamsh4 commented Apr 27, 2025

Attempting to run this on M4 Max with the instructions above (same instructions on the README from the PR repo), I consistently fail when trying to generate using gradio (pytohn3 app.py --device mps) with

gradio.exceptions.Error: 'Inference failed: probability tensor contains either `inf`, `nan` or element < 0'

@felipeff
Copy link

felipeff commented May 1, 2025

It took me a while to figure out, but the Python venv setup for the project installs Pytorch 2.6.0.
I had to run:

pip3 install torch torchaudio torch-stoi --upgrade

to upgrade to the latest version 2.7.0.

After that, I was able to successfully run/validate the code

@devnoff
Copy link
Author

devnoff commented May 1, 2025

https://velog.io/@devnoff/Dia-Text-to-Speech-Model-macOS-%EC%A7%80%EC%9B%90-%EC%9E%91%EC%97%85-%EA%B3%BC%EC%A0%95

참고로, 이번 작업을 수행한 과정을 기록한 블로그 글입니다.
(For reference, here is a blog post documenting the process of doing this.)

@felipeff
Copy link

felipeff commented May 1, 2025

https://velog.io/@devnoff/Dia-Text-to-Speech-Model-macOS-%EC%A7%80%EC%9B%90-%EC%9E%91%EC%97%85-%EA%B3%BC%EC%A0%95

참고로, 이번 작업을 수행한 과정을 기록한 블로그 글입니다. (For reference, here is a blog post documenting the process of doing this.)

Considering that you already have a conditional setup in the poetry config file, it would be a good idea for you to install torch 2.7.0 if you're on macos instead of the current 2.6 config. This would prevent the issues that I and others in the 2 discussion threads that exist with people reporting that this PR did not work for them

@1TommyCheung
Copy link

Checked on

  Model Name: MacBook Pro
  Model Identifier: MacBookPro18,2
  Model Number: Z14V001TCD/A
  Chip: Apple M1 Max
  Total Number of Cores: 10 (8 performance and 2 efficiency)
  Memory: 64 GB
$ git clone [email protected]:nari-labs/dia.git
$ git remote add devnoff [email protected]:devnoff/dia.git
$ git fetch devnoff mac
$ git co devnoff/mac
$ python3.10 -m venv ~/venv/dia
$ source ~/venv/dia/bin/activate
$ pip install -e .
$ python --version
    Python 3.10.16
$ python app.py

Using device: mps
Loading Nari model...
config.json: 100%|███████████████████████████████████████████████████████| 941/941 [00:00<00:00, 1.27MB/s]
dia-v0_1.pth: 100%|██████████████████████████████████████████████████| 6.44G/6.44G [04:42<00:00, 22.8MB/s]
/Users/maslovw/venv/dia/lib/python3.10/site-packages/torch/nn/utils/weight_norm.py:143: FutureWarning: `torch.nn.utils.weight_norm` is deprecated in favor of `torch.nn.utils.parametrizations.weight_norm`.
  WeightNorm.apply(module, name, dim)
Launching Gradio interface...
* Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.
--- Inside _prepare_generation ---
Type of self.config: <class 'dia.config.DiaConfig'>
Content of self.config (or keys): dict_keys(['version', 'model', 'training', 'data'])
--- End Debug Print ---
Generation finished in 44.50 seconds.
Resampled audio from 387584 to 412323 samples for 0.94x speed.
Audio conversion successful. Final shape: (412323,), Sample Rate: 44100
Converted audio to int16 for Gradio output.

Generation of an example is successful

Specifically for any one who is trying to replicate this, you have to clone @devnoff mac branch:

git clone --single-branch --branch mac https://github.com/devnoff/dia.git

Follow the rest of the instructions (personally I use the exact python version 3.10.16 for the venv/conda env). Works great. @devnoff 정말 감사합니다. 훌륭해요 Vibe Coding!

@cedricferry
Copy link

Device: Apple M3 Pro, 36GB, macOS sonoma

git clone --single-branch --branch mac https://github.com/devnoff/dia.git
uv run app.py --device=mps

It seems to work, I see GPU usage going up (80-95%). But eventually failed with this error:

Inference failed: Output channels > 65536 not supported at the MPS device.

@tejas-hosamani
Copy link

tejas-hosamani commented Jul 7, 2025

I am getting this error, any idea why?

image

Edit:
I ran this command:
pip3 install torch torchaudio torch-stoi --upgrade

Now I am getting this:
image

@robbiemu
Copy link

I am getting this error, any idea why?

image Edit: I ran this command: `pip3 install torch torchaudio torch-stoi --upgrade`

Now I am getting this: image

does this work for you?

    compute_dtype = torch.float16 if self.device == "cuda" else torch.float32

    self.model = Dia.from_pretrained(
        model_checkpoint, compute_dtype=compute_dtype, device=self.device
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants