opção

cupynumeric-install

NVIDIA/skills NVIDIA/skills

Instale e verifique o cuPyNumeric para Python usando o conda ou o pip, incluindo verificações de uso da GPU.

...Expandir tudo
32
Tempo atualizado 23 de Setembro de 2026

Instalação do cuPyNumeric (usuário)

Objetivo

Utilize esta habilidade para instalar o cuPyNumeric para uso em Python e para verificar se a instalação realmente funciona (incluindo o uso da GPU). Aplique-a sempre que um usuário desejar executar o cuPyNumeric via conda ou pip. Não a utilize para compilar a partir do código-fonte (para modificar ou contribuir) — isso está fora do escopo.

Regras obrigatórias

  • Nunca execute instalações. Não execute `pip install`, `conda install` ou qualquer instalador. Exiba o comando; deixe que o usuário o execute.
  • Sempre isole. Não faça instalações no conda base, no Python do sistema ou em ambientes globais compartilhados.
  • Detecte antes de recomendar. Verificações de ` --version ` somente de leitura são aceitáveis.

Pré-requisitos

Confirme estes requisitos de sistema antes de recomendar qualquer instalação:

  • GPU: Capacidade de Computação ≥ 7.0 (Volta+). Também é compatível apenas com CPU.
  • CUDA: 12.2+.
  • SO: Linux (x86_64 / aarch64), macOS aarch64 (apenas pacotes pip), Windows via WSL.
  • Python: 3.11 a 3.14 no Linux; 3.11 a 3.13 no macOS aarch64.
  • conda: ≥ 24.1 (somente no caminho do conda).
  • Gerenciador de pacotes: conda (recomendado pelo desenvolvedor original) ou pip. Se nenhum dos dois estiver presente, instale um deles primeiro (consulte as instruções).

Instruções

Siga estas etapas na ordem: confirme os pré-requisitos, responda às perguntas de escopo, instale pelo caminho escolhido e, por fim, verifique.

Verifique antes de instalar

  1. Gerenciador de pacotes? Verifique ` conda --version ` e `pip --version`. Prefira o conda (recomendado pelo desenvolvedor original); use o pip como alternativa.
  2. Ambiente de destino? Máquina com GPU, laptop apenas com CPU, nuvem, contêiner ou remoto/servidor.
  3. Versão do CUDA? Pergunte apenas ao forçar a variante com GPU em um host sem uma GPU visível. Verifique com `nvidia-smi ` / `nvcc --version`.

Inicialização — instale primeiro um gerenciador de pacotes

Se nem o conda nem o pip estiverem disponíveis, instale um deles. Forneça o comando e o link da documentação; não o execute — o `curl | bash ` requer a confiança do usuário.

Recomendado: Miniforge (conda completo, padrão do conda-forge)

curl -L -O "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
bash "Miniforge3-$(uname)-$(uname -m).sh"

Documentação: https://github.com/conda-forge/miniforge

Alternativa: Python + pip

Instale o Python usando o gerenciador de pacotes do seu sistema operacional (apt/dnf/brew) ou https://www.python.org/downloads/. Se o pip não estiver instalado em uma instalação existente do Python: python -m ensurepip --upgrade.

Após a instalação, abra um novo shell para que o binário esteja no PATH.

Instalação — caminho do conda

conda create -n cupynumeric -c conda-forge -c legate cupynumeric
conda activate cupynumeric

Em um ambiente já existente: conda install -c conda-forge -c legate cupynumeric.

O conda seleciona automaticamente a variante GPU ou CPU com base no funcionamento do `nvidia-smi` no momento da instalação. Para substituir essa escolha, veja abaixo.

Forçar a variante com GPU

Defina CONDA_OVERRIDE_CUDA somente quando nenhuma GPU estiver visível no momento da instalação (por exemplo, ao criar um contêiner para um host com GPU). Use a versão do CUDA do host de execução:

CONDA_OVERRIDE_CUDA="12.2" conda install -c conda-forge -c legate cupynumeric

Nightly (menos validado)

conda install -c conda-forge -c legate-nightly cupynumeric

Instalação — caminho do pip

python -m venv .venv
source .venv/bin/activate
pip install nvidia-cupynumeric

Verificar

Teste básico (sempre executar)

Execute um script autônomo pelo iniciador do Legate — não é necessário fazer checkout do repositório.

TMP=$(mktemp -d)
cat > "$TMP/smoke.py" <<'EOF'
import cupynumeric as np
a = np.arange(10)
b = np.ones((4, 4))
print("soma:", a.sum())            # resultado esperado: 45
print("matmul:", (b @ b).sum())   # resultado esperado: 64,0
EOF
legate "$TMP/smoke.py"
rm -rf "$TMP"

Espera-se que soma: 45 e matmul: 64,0. Se o comando `legate` estiver faltando, o ambiente não está ativado — consulte a seção "Solução de problemas".

Verificação do uso da GPU (obrigatória quando há uma GPU compatível)

A aprovação no teste de fumaça não comprova o uso da GPU — uma instalação da variante de CPU em um sistema com GPU também produz resultados corretos. Execute ambas as etapas.

1. Force a inicialização da GPU. O comando ` legate --gpus N ` solicita N GPUs; falha rapidamente se nenhuma GPU estiver visível ou se a variante para CPU estiver instalada.

TMP=$(mktemp -d)
cat > "$TMP/check.py" <<'EOF'
import cupynumeric as np
print(np.ones((4096, 4096)).sum())
EOF
legate --gpus 1 "$TMP/check.py"
rm -rf "$TMP"

O resultado esperado é 16777216,0. Se você encontrar o driver CUDA, a libcudart ou nenhuma GPU disponível, significa que a variante para CPU está instalada; reinstale com CONDA_OVERRIDE_CUDA.

2. Confirme se a GPU foi acionada. Execute um loop de matmul com limite de tempo junto com o nvidia-smi, tudo a partir de um único shell — sem a necessidade de um segundo terminal:

TMPDIR_GPU=$(mktemp -d)
SCRIPT="$TMPDIR_GPU/cupynumeric_gpu_check.py"
cat > "$SCRIPT" <<'EOF'
import cupynumeric as np, time
a = np.ones((10000, 10000))
deadline = time.time() + 20
iters = 0
while time.time() < deadline:
    b = a @ a
    _ = float(b.sum())   # força a sincronização para que a matmul realmente seja executada
    iters += 1
print("iters:", iters)
EOF
legate --gpus 1 "$SCRIPT" &
WORKLOAD=$!
sleep 5                                     # intervalo para inicialização do Legate
for _ in $(seq 10); do                      # 10 amostras a cada 1 s — cobre a inicialização lenta
  nvidia-smi --query-gpu=utilization.gpu,memory.used --format=csv,noheader
  sleep 1
done
wait "$WORKLOAD"
rm -rf "$TMPDIR_GPU"

É de se esperar que memory.used esteja na faixa de GiB na maioria das amostras e que utilization.gpu apresente valores significativos em várias delas. Se ambos permanecerem na linha de base em todas as amostras, a variante da GPU não está instalada — verifique conda list cupynumeric para *_gpu (não *_cpu).

Receitas mais detalhadas

Consulte verification_examples.md para verificações com múltiplas GPUs, fallback para CPU, contêineres e solução de problemas.

Limitações

  • Não misture conda e pip em um mesmo ambiente. A mistura substitui a primeira instalação e causa falha na importação. Para alternar, execute primeiro `pip uninstall nvidia-cupynumeric ` ou `conda remove cupynumeric `.
  • Use o lançador “legate” para execuções com múltiplas GPUs/múltiplos ranks. O Python puro é executado em um único processo: `legate --gpus 2 script.py`.
  • Force a variante de GPU em um host apenas com CPU usando CONDA_OVERRIDE_CUDA. Caso contrário, o conda seleciona automaticamente a variante de CPU ou GPU a partir do nvidia-smi no momento da instalação.
  • Requer Volta ou versão mais recente. Pascal (GTX 10xx / P100) não é compatível.
  • Verifique se ` conda --version ` é≥ 24.1. Versões mais antigas prejudicam silenciosamente a seleção de variantes.
  • Trate multi-nó / MPI / UCX como fora do escopo. Consulte https://docs.nvidia.com/legate/latest/networking-wheels.html e https://docs.nvidia.com/legate/latest/mpi-wrapper.html.

Solução de problemas

  • ModuleNotFoundError: Nenhum módulo chamado 'cupynumeric' → Execute `which python ` e `pip list | grep cupynumeric ` (ou `conda list | grep cupynumeric`) no mesmo shell para identificar a incompatibilidade de ambiente.
  • Erro de importação mencionando CUDA / libcudart → Reinstale com CONDA_OVERRIDE_CUDA=""; a variante para CPU está em uma máquina com GPU, ou as versões do CUDA não são compatíveis.
  • legate: comando não encontrado → Ative o ambiente e, em seguida, execute `which legate ` para confirmar.
  • Mais lento que o NumPy em um laptop → É normal que isso ocorra em problemas pequenos (sobrecarga do Legate por tarefa). Consulte o FAQ do cuPyNumeric.

Veja também

  • references/verification_examples.md — receitas de verificação e solução de problemas.
  • Documentação original: https://docs.nvidia.com/cupynumeric/latest/installation.html
  • Requisitos do Legate: https://docs.nvidia.com/legate/latest/installation.html
Ver no GitHub
---
name: cupynumeric-install
description: Install and verify cuPyNumeric for Python using conda or pip, including GPU usage checks.
license: CC-BY-4.0 OR Apache-2.0
---

# cuPyNumeric Install (user)

## Purpose

Use this skill to install cuPyNumeric for *use* from Python and to verify the install actually works (including GPU usage). Apply it whenever a user wants cuPyNumeric running via conda or pip. Do not use it to build from source (to modify or contribute) — that is out of scope.

## Mandatory rules

- **Never run installs.** Do not run `pip install`, `conda install`, or any installer. Print the command; let the user run it.
- **Always isolate.** No installs into base conda, system Python, or shared global envs.
- **Detect before recommending.** Read-only `--version` checks are fine.

## Prerequisites

Confirm these system requirements before recommending any install:

- **GPU**: Compute Capability ≥ 7.0 (Volta+). CPU-only also supported.
- **CUDA**: 12.2+.
- **OS**: Linux (x86_64 / aarch64), macOS aarch64 (pip wheels only), Windows via WSL.
- **Python**: 3.11 through 3.14 on Linux; 3.11 through 3.13 on macOS aarch64.
- **conda**: ≥ 24.1 (conda path only).
- **Package manager**: conda (upstream-recommended) or pip. If neither is present, bootstrap one first (see Instructions).

## Instructions

Follow these steps in order: confirm the prerequisites, ask the scoping questions, install via the chosen path, then verify.

### Ask before installing

1. **Package manager?** Check `conda --version` and `pip --version`. Prefer conda (upstream-recommended); fall back to pip.
1. **Env target?** GPU machine, CPU-only laptop, cloud, container, or remote/server.
1. **CUDA version?** Ask only when forcing the GPU variant on a host without a visible GPU. Check with `nvidia-smi` / `nvcc --version`.

### Bootstrap — install a package manager first

If neither `conda` nor `pip` is available, install one. **Provide the command and the docs link; do not run it** — `curl | bash` requires user trust.

#### Recommended: Miniforge (full conda, conda-forge default)

```bash
curl -L -O "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
bash "Miniforge3-$(uname)-$(uname -m).sh"
```

Docs: https://github.com/conda-forge/miniforge

#### Alternative: Python + pip

Install Python from your OS package manager (apt/dnf/brew) or https://www.python.org/downloads/. If pip is missing on an existing Python: `python -m ensurepip --upgrade`.

After installing, **open a new shell** so the binary is on PATH.

### Install — conda path

```bash
conda create -n cupynumeric -c conda-forge -c legate cupynumeric
conda activate cupynumeric
```

Into an existing env: `conda install -c conda-forge -c legate cupynumeric`.

conda auto-selects the GPU vs CPU variant from whether `nvidia-smi` works at install time. To override that, see below.

#### Force the GPU variant

Set `CONDA_OVERRIDE_CUDA` only when no GPU is visible at install time (e.g. building a container for a GPU host). Use the runtime host's CUDA version:

```bash
CONDA_OVERRIDE_CUDA="12.2" conda install -c conda-forge -c legate cupynumeric
```

#### Nightly (less validated)

```bash
conda install -c conda-forge -c legate-nightly cupynumeric
```

### Install — pip path

```bash
python -m venv .venv
source .venv/bin/activate
pip install nvidia-cupynumeric
```

### Verify

#### Smoke test (always run)

Run a self-contained script through the `legate` launcher — no repo checkout needed.

```bash
TMP=$(mktemp -d)
cat > "$TMP/smoke.py" <<'EOF'
import cupynumeric as np
a = np.arange(10)
b = np.ones((4, 4))
print("sum:", a.sum())            # expect 45
print("matmul:", (b @ b).sum())   # expect 64.0
EOF
legate "$TMP/smoke.py"
rm -rf "$TMP"
```

Expect `sum: 45` and `matmul: 64.0`. If `legate` is missing, the env is not activated — see Troubleshooting.

#### GPU usage check (mandatory when a supported GPU is present)

A passing smoke test does **not** prove GPU usage — a CPU-variant install on a GPU box produces correct results too. Run both steps.

**1. Force a GPU launch.** `legate --gpus N` requests N GPUs; fails fast if no GPU is visible or the CPU variant is installed.

```bash
TMP=$(mktemp -d)
cat > "$TMP/check.py" <<'EOF'
import cupynumeric as np
print(np.ones((4096, 4096)).sum())
EOF
legate --gpus 1 "$TMP/check.py"
rm -rf "$TMP"
```

Expect `16777216.0`. If you see `CUDA driver`, `libcudart`, or `no GPUs available`, the CPU variant is installed; reinstall with `CONDA_OVERRIDE_CUDA`.

**2. Confirm the GPU was touched.** Run a deadline-bounded matmul loop alongside `nvidia-smi`, all from one shell — no second-terminal race:

```bash
TMPDIR_GPU=$(mktemp -d)
SCRIPT="$TMPDIR_GPU/cupynumeric_gpu_check.py"
cat > "$SCRIPT" <<'EOF'
import cupynumeric as np, time
a = np.ones((10000, 10000))
deadline = time.time() + 20
iters = 0
while time.time() < deadline:
    b = a @ a
    _ = float(b.sum())   # force sync so the matmul actually runs
    iters += 1
print("iters:", iters)
EOF
legate --gpus 1 "$SCRIPT" &
WORKLOAD=$!
sleep 5                                     # buffer for Legate startup
for _ in $(seq 10); do                      # 10 samples at 1s — covers slow startup
  nvidia-smi --query-gpu=utilization.gpu,memory.used --format=csv,noheader
  sleep 1
done
wait "$WORKLOAD"
rm -rf "$TMPDIR_GPU"
```

Expect `memory.used` in the GiB range across most samples and non-trivial `utilization.gpu` in several. If both stay at baseline across every sample, the GPU variant is not installed — check `conda list cupynumeric` for `*_gpu` (not `*_cpu`).

#### Deeper recipes

See [verification_examples.md](references/verification_examples.md) for multi-GPU checks, CPU fallback, container, and troubleshooting.

## Limitations

- **Don't mix conda and pip in one env.** Mixing overrides the first install and breaks at import. To switch, run `pip uninstall nvidia-cupynumeric` or `conda remove cupynumeric` first.
- **Use the `legate` launcher for multi-GPU / multi-rank runs.** Plain `python` runs single-process: `legate --gpus 2 script.py`.
- **Force the GPU variant on a CPU-only host with `CONDA_OVERRIDE_CUDA`.** conda otherwise auto-selects the CPU or GPU variant from `nvidia-smi` at install time.
- **Require Volta or newer.** Pascal (GTX 10xx / P100) is unsupported.
- **Verify `conda --version` ≥ 24.1.** Older releases silently break variant selection.
- **Treat multi-node / MPI / UCX as out of scope.** Defer to https://docs.nvidia.com/legate/latest/networking-wheels.html and https://docs.nvidia.com/legate/latest/mpi-wrapper.html.

## Troubleshooting

- **`ModuleNotFoundError: No module named 'cupynumeric'`** → Run `which python` and `pip list | grep cupynumeric` (or `conda list | grep cupynumeric`) from the same shell to find the env mismatch.
- **`ImportError` mentioning CUDA / `libcudart`** → Reinstall with `CONDA_OVERRIDE_CUDA="<your-cuda-version>"`; the CPU variant is on a GPU box, or CUDA versions are mismatched.
- **`legate: command not found`** → Activate the env, then run `which legate` to confirm.
- **Slower than NumPy on a laptop** → Expect this for small problems (Legate per-task overhead). See the cuPyNumeric FAQ.

## See also

- [references/verification_examples.md](references/verification_examples.md) — verification + troubleshooting recipes.
- Upstream docs: https://docs.nvidia.com/cupynumeric/latest/installation.html
- Legate requirements: https://docs.nvidia.com/legate/latest/installation.html

Instalar cupynumeric-install

Baixe e descompacte os arquivos de habilidades no diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

git clone https://github.com/NVIDIA/skills/tree/main/skills/cupynumeric-install # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuração rápida: Copie a pasta da habilidade para .claude/skills/ O Claude detectará e utilizará automaticamente a habilidade
Repositório NVIDIA/skills

Habilidades relacionadas

microservices-patterns
Tempo atualizado 29 de Junho de 2026
jpa-patterns
Tempo atualizado 30 de Junho de 2026
fabric-lakehouse
Tempo atualizado 30 de Junho de 2026
prisma-expert
Tempo atualizado 29 de Junho de 2026
OR