Importante
bigdl-llm agora se tornou ipex-llm , e nosso desenvolvimento futuro passará para o projeto IPEX-LLM.
O BIGDL escala perfeitamente seus aplicativos de análise de dados e AI do laptop para a nuvem, com as seguintes bibliotecas:
LLM (depreciado - use ipex -llm) : Otimizaed Language Model Library para Intel CPU e GPU
ORCA: Distribuído Big Data & AI (TF & Pytorch) Pipeline no Spark e Ray
Nano: aceleração transparente de programas Tensorflow e Pytorch na Intel CPU/GPU
Dllib: “equivalente ao spark mllib” para aprendizado profundo
Chronos: análise de séries temporais escaláveis usando automl
Friesian: sistemas de recomendação de ponta a ponta
PPML: seguro Big Data e AI (com segurança de hardware SGX/TDX)
Para mais informações, você pode ler os documentos.
Fluxograma TD;
Recurso1 {{hw garantiu big data & ai?}};
Recurso1-- Não-> Feature2 {{python vs. scala/java?}};
Recurso1-- "Sim"-> referendpml ([<em> <strong> ppml </strong> </em>]);
Feature2-- Python-> Feature3 {{que tipo de aplicativo?}};
FeChe2-- Scala/Java-> referenciado ([<em> <strong> dllib </strong> </em>]);
Recurso3-- "Modelo de Idioma Grande"-> referllm ([<em> <strong> llm </strong> </em>]);
Recurso3-- "big data + ai (tf/pytorch)"-> referorca ([<em> <strong> orca </strong> </em>]);
Recurso3-Acelere o tensorflow/pytorch-> refernano ([<em> <strong> nano </strong> </em>]);
Recurso3-DL para Spark mllib-> referdllib2 ([<em> <strong> dllib </strong> </em>]);
Recurso3-- Framework de App de alto nível-> Recurso4 {{domain?}};
Feature4-- Série Tempo-> ReferChronos ([<em> <strong> Chronos </strong> </em>]);
Recurso4-Sistema de Recomendamento-> Referenciefriesian ([<em> <strong> Friesian </strong> </em>]);
Clique em referllm "https://github.com/intel-analytics/ipex-llm"
Clique em Refernano "https://github.com/intel-analytics/bigdl-2.x#nano"
Clique em Referorca "https://github.com/intel-analytics/bigdl-2.x#orca"
Clique em Referdllib "https://github.com/intel-analytics/bigdl-2.x#dllib"
Clique em Referdllib2 "https://github.com/intel-analytics/bigdl-2.x#dllib"
Clique em ReferChronos "https://github.com/intel-analytics/bigdl-2.x#chronos"
Clique em ReferFriesian "https://github.com/intel-analytics/bigdl-2.x#friesian"
Clique em Referpppml "https://github.com/intel-analytics/bigdl-2.x#ppml"
ClassDef referenceTyle1 Fill:#5099CE, AVC:#5099CE;
ClassDef Recurso Preencher:#fff, AVC:#08409C, Width: 1px;
Classe referllm, refernano, referorca, referdllib, referdllib2, refercronos, referfriesian, referppml referenceyle1;
Classe Feature1, Feequine2, Feature3, Feature4, Feature5, Feature6, Feature7 Recurso;
Para instalar o BIGDL, recomendamos o uso do ANIFORAÇÃO CONDA:
conda create -n my_env
conda activate my_env
pip install bigdl Para instalar o mais recente edifício noturno, use pip install --pre --upgrade bigdl ; Consulte Guia do usuário Python e Scala para obter mais detalhes.
Para instalar cada biblioteca individual, como o Chronos, use pip install bigdl-chronos ; Consulte o site do documento para obter mais detalhes.
A biblioteca ORCA escala perfeitamente os programas Tensorflow , Pytorch ou Openvino de nós únicos em clusters grandes (de modo a processar big data distribuído).
Você pode criar programas de dados distribuídos de ponta a ponta e AI usando ORCA em 4 etapas simples:
# 1. Initilize Orca Context (to run your program on K8s, YARN or local laptop)
from bigdl . orca import init_orca_context , OrcaContext
sc = init_orca_context ( cluster_mode = "k8s" , cores = 4 , memory = "10g" , num_nodes = 2 )
# 2. Perform distribtued data processing (supporting Spark DataFrames,
# TensorFlow Dataset, PyTorch DataLoader, Ray Dataset, Pandas, Pillow, etc.)
spark = OrcaContext . get_spark_session ()
df = spark . read . parquet ( file_path )
df = df . withColumn ( 'label' , df . label - 1 )
...
# 3. Build deep learning models using standard framework APIs
# (supporting TensorFlow, PyTorch, Keras, OpenVino, etc.)
from tensorflow import keras
...
model = keras . models . Model ( inputs = [ user , item ], outputs = predictions )
model . compile (...)
# 4. Use Orca Estimator for distributed training/inference
from bigdl . orca . learn . tf . estimator import Estimator
est = Estimator . from_keras ( keras_model = model )
est . fit ( data = df ,
feature_cols = [ 'user' , 'item' ],
label_cols = [ 'label' ],
...)Consulte o Orca User Guide, bem como o Tensorflow e o Pytorch QuickStars, para obter mais detalhes.
Além disso, você também pode executar programas de raio padrão no Spark Cluster usando Rayonspark no ORCA.
Você pode não apenas executar o programa Ray no Spark Cluster, mas também escrever o código de raio embutido com o código Spark (para processar os RDDs ou quadros de dados Spark in Memory) usando o Rayonspark na ORCA.
# 1. Initilize Orca Context (to run your program on K8s, YARN or local laptop)
from bigdl . orca import init_orca_context , OrcaContext
sc = init_orca_context ( cluster_mode = "yarn" , cores = 4 , memory = "10g" , num_nodes = 2 , init_ray_on_spark = True )
# 2. Distribtued data processing using Spark
spark = OrcaContext . get_spark_session ()
df = spark . read . parquet ( file_path ). withColumn (...)
# 3. Convert Spark DataFrame to Ray Dataset
from bigdl . orca . data import spark_df_to_ray_dataset
dataset = spark_df_to_ray_dataset ( df )
# 4. Use Ray to operate on Ray Datasets
import ray
@ ray . remote
def consume ( data ) -> int :
num_batches = 0
for batch in data . iter_batches ( batch_size = 10 ):
num_batches += 1
return num_batches
print ( ray . get ( consume . remote ( dataset )))Consulte o Rayonspark User Guide e o QuickStart para obter mais detalhes.
Você pode acelerar transparentemente seus programas Tensorflow ou Pytorch no seu laptop ou servidor usando o Nano . Com alterações mínimas de código, o Nano aplica automaticamente as otimizações modernas da CPU (por exemplo, SIMD, multiprocessamento, baixa precisão, etc.) ao código de fluxo de tensor e pytorch padrão, com aceleração até 10x.
Você pode otimizar automaticamente um modelo Pytorch treinado para inferência ou implantação usando o Nano :
model = ResNet18 (). load_state_dict (...)
train_dataloader = ...
val_dataloader = ...
def accuracy ( pred , target ):
...
from bigdl . nano . pytorch import InferenceOptimizer
optimizer = InferenceOptimizer ()
optimizer . optimize ( model ,
training_data = train_dataloader ,
validation_data = val_dataloader ,
metric = accuracy )
new_model , config = optimizer . get_best_model ()
optimizer . summary () A saída do optimizer.summary() será algo como:
-------------------------------- ---------------------- -------------- ----------------------
| method | status | latency(ms) | metric value |
-------------------------------- ---------------------- -------------- ----------------------
| original | successful | 45.145 | 0.975 |
| bf16 | successful | 27.549 | 0.975 |
| static_int8 | successful | 11.339 | 0.975 |
| jit_fp32_ipex | successful | 40.618 | 0.975* |
| jit_fp32_ipex_channels_last | successful | 19.247 | 0.975* |
| jit_bf16_ipex | successful | 10.149 | 0.975 |
| jit_bf16_ipex_channels_last | successful | 9.782 | 0.975 |
| openvino_fp32 | successful | 22.721 | 0.975* |
| openvino_int8 | successful | 5.846 | 0.962 |
| onnxruntime_fp32 | successful | 20.838 | 0.975* |
| onnxruntime_int8_qlinear | successful | 7.123 | 0.981 |
-------------------------------- ---------------------- -------------- ----------------------
* means we assume the metric value of the traced model does not change, so we don't recompute metric value to save time.
Optimization cost 60.8s in total.
model = ResNet18 ()
optimizer = torch . optim . SGD (...)
train_loader = ...
val_loader = ...
from bigdl . nano . pytorch import TorchNano
# Define your training loop inside `TorchNano.train`
class Trainer ( TorchNano ):
def train ( self ):
# call `setup` to prepare for model, optimizer(s) and dataloader(s) for accelerated training
model , optimizer , ( train_loader , val_loader ) = self . setup ( model , optimizer ,
train_loader , val_loader )
for epoch in range ( num_epochs ):
model . train ()
for data , target in train_loader :
optimizer . zero_grad ()
output = model ( data )
# replace the loss.backward() with self.backward(loss)
loss = loss_fuc ( output , target )
self . backward ( loss )
optimizer . step ()
# Accelerated training (IPEX, BF16 and Multi-Instance Training)
Trainer ( use_ipex = True , precision = 'bf16' , num_processes = 2 ). train ()Consulte o Guia do usuário do Nano e o Tutotial para obter mais detalhes.
Com o DLLIB , você pode escrever aplicativos de aprendizado profundo distribuídos como programas Standard ( Scala ou Python ), usando as mesmas APIs de spark dataframes e ml pipeline .
Você pode criar aplicativos de aprendizado profundo distribuídos para Spark usando APIs Dllib Scala em 3 etapas simples:
// 1. Call `initNNContext` at the beginning of the code:
import com . intel . analytics . bigdl . dllib . NNContext
val sc = NNContext .initNNContext()
// 2. Define the deep learning model using Keras-style API in DLlib:
import com . intel . analytics . bigdl . dllib . keras . layers . _
import com . intel . analytics . bigdl . dllib . keras . Model
val input = Input [ Float ](inputShape = Shape ( 10 ))
val dense = Dense [ Float ]( 12 ).inputs(input)
val output = Activation [ Float ]( " softmax " ).inputs(dense)
val model = Model (input, output)
// 3. Use `NNEstimator` to train/predict/evaluate the model using Spark DataFrame and ML pipeline APIs
import org . apache . spark . sql . SparkSession
import org . apache . spark . ml . feature . MinMaxScaler
import org . apache . spark . ml . Pipeline
import com . intel . analytics . bigdl . dllib . nnframes . NNEstimator
import com . intel . analytics . bigdl . dllib . nn . CrossEntropyCriterion
import com . intel . analytics . bigdl . dllib . optim . Adam
val spark = SparkSession .builder().getOrCreate()
val trainDF = spark.read.parquet( " train_data " )
val validationDF = spark.read.parquet( " val_data " )
val scaler = new MinMaxScaler ().setInputCol( " in " ).setOutputCol( " value " )
val estimator = NNEstimator (model, CrossEntropyCriterion ())
.setBatchSize( 128 ).setOptimMethod( new Adam ()).setMaxEpoch( 5 )
val pipeline = new Pipeline ().setStages( Array (scaler, estimator))
val pipelineModel = pipeline.fit(trainDF)
val predictions = pipelineModel.transform(validationDF)Você pode criar aplicativos de aprendizado profundo distribuídos para Spark usando APIs Dllib Python em 3 etapas simples:
# 1. Call `init_nncontext` at the beginning of the code:
from bigdl . dllib . nncontext import init_nncontext
sc = init_nncontext ()
# 2. Define the deep learning model using Keras-style API in DLlib:
from bigdl . dllib . keras . layers import Input , Dense , Activation
from bigdl . dllib . keras . models import Model
input = Input ( shape = ( 10 ,))
dense = Dense ( 12 )( input )
output = Activation ( "softmax" )( dense )
model = Model ( input , output )
# 3. Use `NNEstimator` to train/predict/evaluate the model using Spark DataFrame and ML pipeline APIs
from pyspark . sql import SparkSession
from pyspark . ml . feature import MinMaxScaler
from pyspark . ml import Pipeline
from bigdl . dllib . nnframes import NNEstimator
from bigdl . dllib . nn . criterion import CrossEntropyCriterion
from bigdl . dllib . optim . optimizer import Adam
spark = SparkSession . builder . getOrCreate ()
train_df = spark . read . parquet ( "train_data" )
validation_df = spark . read . parquet ( "val_data" )
scaler = MinMaxScaler (). setInputCol ( "in" ). setOutputCol ( "value" )
estimator = NNEstimator ( model , CrossEntropyCriterion ())
. setBatchSize ( 128 )
. setOptimMethod ( Adam ())
. setMaxEpoch ( 5 )
pipeline = Pipeline ( stages = [ scaler , estimator ])
pipelineModel = pipeline . fit ( train_df )
predictions = pipelineModel . transform ( validation_df )Consulte os guias do usuário do Dllib NNFRames e Keras API para obter mais detalhes.
A biblioteca Chronos facilita a criação de aplicativos de análise de séries temporais rápidas, precisas e escaláveis (com o Automl).
Você pode treinar um meteorologista da série temporal usando Chronos em 3 etapas simples:
from bigdl . chronos . forecaster import TCNForecaster
from bigdl . chronos . data . repo_dataset import get_public_dataset
# 1. Process time series data using `TSDataset`
tsdata_train , tsdata_val , tsdata_test = get_public_dataset ( name = 'nyc_taxi' )
for tsdata in [ tsdata_train , tsdata_val , tsdata_test ]:
data . roll ( lookback = 100 , horizon = 1 )
# 2. Create a `TCNForecaster` (automatically configured based on train_data)
forecaster = TCNForecaster . from_tsdataset ( train_data )
# 3. Train the forecaster for prediction
forecaster . fit ( train_data )
pred = forecaster . predict ( test_data ) Para aplicar o Automl, use AutoTSEstimator em vez de analistas normais.
# Create and fit an `AutoTSEstimator`
from bigdl . chronos . autots import AutoTSEstimator
autotsest = AutoTSEstimator ( model = "tcn" , future_seq_len = 10 )
tsppl = autotsest . fit ( data = tsdata_train , validation_data = tsdata_val )
pred = tsppl . predict ( tsdata_test )Consulte o Guia do Usuário do Chronos e Iniciar rápido para obter mais detalhes.
A biblioteca Friesian facilita a criação do sistema de recomendação de ponta a ponta em larga escala (incluindo transformação de recursos offline e transing, recurso próximo e atualização de modelo e pipeline de servir on-line ).
Veja a Freisian ReadMe para mais detalhes.
O BIGDL PPML fornece um ambiente de cluster confiável protegido de hardware (Intel SGX) para executar aplicativos Big Data e AI distribuídos (de maneira segura em nuvem pública ou privada).
Consulte o Guia do Usuário do PPML e o tutorial para obter mais detalhes.
Se você achou o BIGDL útil para o seu projeto, pode citar nossos papéis da seguinte maneira:
@INPROCEEDINGS{9880257,
title={BigDL 2.0: Seamless Scaling of AI Pipelines from Laptops to Distributed Cluster},
author={Dai, Jason Jinquan and Ding, Ding and Shi, Dongjie and Huang, Shengsheng and Wang, Jiao and Qiu, Xin and Huang, Kai and Song, Guoqiong and Wang, Yang and Gong, Qiyuan and Song, Jiaming and Yu, Shan and Zheng, Le and Chen, Yina and Deng, Junwei and Song, Ge},
booktitle={2022 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
year={2022},
pages={21407-21414},
doi={10.1109/CVPR52688.2022.02076}
}
@INPROCEEDINGS{10.1145/3357223.3362707,
title = {BigDL: A Distributed Deep Learning Framework for Big Data},
author = {Dai, Jason Jinquan and Wang, Yiheng and Qiu, Xin and Ding, Ding and Zhang, Yao and Wang, Yanzhang and Jia, Xianyan and Zhang, Cherry Li and Wan, Yan and Li, Zhichao and Wang, Jiao and Huang, Shengsheng and Wu, Zhongyuan and Wang, Yang and Yang, Yuhao and She, Bowen and Shi, Dongjie and Lu, Qi and Huang, Kai and Song, Guoqiong},
booktitle = {Proceedings of the ACM Symposium on Cloud Computing (SoCC)},
year = {2019},
pages = {50–60},
doi = {10.1145/3357223.3362707}
}