Jax accéléré sur Mac – Metal

Jax accéléré sur Mac – Metal

Plug-in en métal

Jax utilise le nouveau plug-in métallique pour fournir une accélération métallique sur les plates-formes Mac. Le plugin métallique utilise le compilateur OpenXLA et le runtime PJRT pour accélérer les charges de travail d'apprentissage automatique JAX sur GPU. Le compilateur OpenXLA abaisse les primitives JAX en un format HLO stable, qui est converti en exécutables MPSGraph et API d'exécution en métal pour expédier en GPU.

Découpe Laser Métal _ Banner _ R3V Laser

Exigences

  • Ordinateurs Mac avec des GPU en silicium Apple ou AMD
  • Python 3.9 ou plus tard
  • Outils de ligne de commande xcode: xcode-select --install

Commencer

Installer

La table ci-dessous suit les versions Jax-Metal et les versions compatibles de MacOS et Jaxlib. La compatibilité entre Jax et Jaxlib est maintenue via Jax.

jax-metal macos jaxlib
0.1.0 Sonoma 14.4+ > = V0.4.26
0.0.7 Sonoma 14.4+ > = V0.4.26
0.0,6 Sonoma 14.4 Beta > = V0.4.22,> V0.4.24
0.0,5 Sonoma 14.2+ > = v0.4.20,> v0.4.22
0.0.4 Sonoma 14.0 v0.4.11
0.0.3 Ventura 13.4.1+, Sonoma 14.0 Beta v0.4.10

Nous vous recommandons d'installer le forfait binaire avec Venv ou Miniconda.

python3 -m venv ~/jax-metal
source ~/jax-metal/bin/activate
python -m pip install -U pip
python -m pip install numpy wheel
python -m pip install jax-metal

Vérifier

python -c 'import jax; print(jax.numpy.arange(10))'

Compatibilité avec Jaxlib

Jjax-Metal est compatible avec la version minimale de Jaxlib suivie dans le tableau ci-dessus. Il peut être exécuté de manière compatible avec des jaxlibs au-delà de la version minimale en définissant la variable d'environnement sur ENABLE_PJRT_COMPATIBILITY=1.

pip install -U jaxlib jax
ENABLE_PJRT_COMPATIBILITY=1 python -c 'import jax; print(jax.numpy.arange(10))'

Exécuter l'inférence sur le modèle Axlearn Fuji

Installer MiniConda

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh; \
	bash Miniconda3-latest-Linux-x86_64.sh; \
	bash

Configuration de Venv

conda create -n axlearn python=3.9
conda activate axlearn
git clone https://github.com/apple/axlearn.git
cd axlearn
pip install -e .
pip install jax-metal

Demo de course

Variable d'environnement JAX_DISABLE_JIT peut être retiré avec les prochaines graines macOS (lorsque le problème sous-jacent est résolu).

JAX_DISABLE_JIT=1 ENABLE_PJRT_COMPATIBILITY=1 CHECKPOINT_PATH=${path_to_checkpoints} python demo.py

# demo.py
import os

import jax
import jax.numpy as jnp
import numpy as np

from axlearn.common.inference import InferenceRunner
from axlearn.experiments import get_named_trainer_config

def get_runner(name, checkpoint_path):
    """Make an inference runner initialized with pre-trained state according to name."""
    trainer_cfg = get_named_trainer_config(
            name,
            config_module=f"axlearn.experiments.text.gpt.c4_trainer",
        )()
    inference_runner_cfg = InferenceRunner.default_config().set(
        name=f"{name}_inference_runner",
        mesh_axis_names=("data", "expert", "fsdp", "seq", "model"),
        mesh_shape=(1, 1, len(jax.devices()), 1, 1),
        model=trainer_cfg.model.set(dtype=jnp.bfloat16),
        inference_dtype=jnp.bfloat16,
    )
    inference_runner_cfg.init_state_builder.dir = checkpoint_path
    inference_runner = inference_runner_cfg.instantiate(parent=None)
    return inference_runner

def predict(inference_runner, inputs_ids):
    """
    Helper method to perform one forward pass for the model.
    """

    input_batches = [{"input_ids": jnp.array(inputs_ids)}]
    for result in inference_runner.run(
        input_batches,
        method="predict",
        prng_key=jax.random.PRNGKey(11),
    ):
        return result["outputs"]

def gen_tokens(inference_runner, inputs_ids, max_new_tokens):
    """
    Helper method to generate multiple tokens for the model.
    """
    batch_size, prompt_len = inputs_ids.shape

    result_len = prompt_len + max_new_tokens
    result = np.zeros(
        (batch_size, result_len), dtype=inputs_ids.dtype)
    result[:, :prompt_len] = inputs_ids

    input_batches = [{"input_ids": jnp.array(inputs_ids),
    "prefix": jnp.array(result)}]

    for result in inference_runner.run(
        input_batches,
        method="sample_decode",
        prng_key=jax.random.PRNGKey(11),
    ):
        return result["outputs"]

def get_data(seq_len, vocab_size, batch_size=1):
    """ Generate random input in shape of [batch, seq] """
    rng = np.random.RandomState(11)
    input_ids = rng.randint(0, vocab_size, (batch_size, seq_len)).astype(np.int32)
    return input_ids

if __name__ == "__main__":
    model_name = 'fuji-7B-v1-single-host'
    checkpoint_path = os.getenv("CHECKPOINT_PATH")
    vocab_size = 32768
    seq_len = 10
    
    model = get_runner(
            model_name,
            checkpoint_path=checkpoint_path,
        )

    input_data = get_data(seq_len, vocab_size)
    print(f'Creating random input ids: {input_data}')

    print("Extracting logits after 1 step.....")
    predict_output = predict(model, input_data)
    logits = predict_output['logits']
    res = np.array(logits).astype(np.float32)
    last_logit = logits[:,-1,:]
    print(f'Last logits are {last_logit}')
    token_id = np.argmax(res[:,-1,:], axis=-1)
    print(f'Predicated token is {token_id}')
    
    max_new_tokens = 5
    print(f'Generating {max_new_tokens} extended tokens.....', )
    decoding_output = gen_tokens(model, input_data, max_new_tokens)
    new_tokens = decoding_output.sequences[:,:, 10:]
    print(f'Extend tokens are {new_tokens}',)

Essai

Découvrez l'état des tests de Jax-Metal grâce à l'action du flux de travail métal dans GitHub Jax.

Actuellement non pris en charge

Le plug-in métallique est expérimental et toutes les fonctionnalités JAX ne peuvent pas être prises en charge. Les problèmes qui sont signalés et suivis peuvent être trouvés dans la liste: https://github.com/google/jax/issues?q=is%3AISSUe+is%3aOpen+Metal

Questions et commentaires

Pour poser des questions et partager les commentaires sur le plug-in Metal, visitez les forums Apple Developer. Vous pouvez également afficher les problèmes GitHub Jax avec l'étiquette «Plugin Apple GPU (Metal)».

Source link

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Panier
Retour en haut
découpe laser pub