python_code
stringlengths 0
992k
| repo_name
stringlengths 8
46
| file_path
stringlengths 5
162
|
---|---|---|
import os
from setuptools import find_packages, setup
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(CURRENT_DIR, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="nucleotide_transformer",
version="0.0.1",
packages=find_packages(),
url="https://github.com/instadeepai/nucleotide-transformer",
license="CC BY-NC-SA 4.0",
author="InstaDeep Ltd",
python_requires=">=3.8",
description="The Nucleotide Transformer: Building and Evaluating "
"Robust Foundation Models for Human Genomics ",
long_description=long_description,
long_description_content_type="text/markdown",
install_requires=[
"absl-py>=1.0.0",
"jax>=0.3.25",
"jaxlib>=0.3.25",
"dm-haiku>=0.0.9",
"numpy>=1.23.5",
"boto3>=1.24.28",
"typing_extensions>=3.10.0",
"joblib>=1.2.0",
"tqdm>=4.56.0",
"regex>=2022.1.18",
],
dependency_links=[
"https://storage.googleapis.com/jax-releases/jax_releases.html",
],
keywords=["Genomics", "Language Model", "Deep Learning", "JAX"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
)
| nucleotide-transformer-main | setup.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
from typing import Any, Callable, Dict, Optional, Tuple
import boto3
import haiku as hk
import joblib
import tqdm
from botocore import UNSIGNED
from botocore.config import Config
from nucleotide_transformer.model import (
NucleotideTransformerConfig,
build_nucleotide_transformer_fn,
)
from nucleotide_transformer.tokenizers import FixedSizeNucleotidesKmersTokenizer
ENV_XDG_CACHE_HOME = "XDG_CACHE_HOME"
DEFAULT_CACHE_DIR = "~/.cache"
def _get_dir() -> str:
"""
Get directory to save files on user machine.
"""
return os.path.expanduser(
os.path.join(
os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), "nucleotide_transformer"
)
)
def download_from_s3_bucket(
s3_client: boto3.session.Session, bucket: str, key: str, filename: str
) -> None:
"""
Download data from the s3 bucket and display downloading progression bar.
Args:
s3_client: Boto3 s3 client
bucket: Bucket name.
key: Path towards file in the bucket.
filename: Path to save file locally.
"""
kwargs = {
"Bucket": bucket,
"Key": key,
}
object_size = s3_client.head_object(**kwargs)["ContentLength"]
with tqdm.tqdm(total=object_size, unit="B", unit_scale=True, desc=filename) as pbar:
with open(filename, "wb") as f:
s3_client.download_fileobj(
Bucket=bucket,
Key=key,
ExtraArgs=None,
Fileobj=f,
Callback=lambda bytes_transferred: pbar.update(bytes_transferred),
)
def download_ckpt_and_hyperparams(model_name: str) -> Tuple[hk.Params, Dict[str, Any]]:
"""
Download checkpoint and hyperparams on kao datacenter.
Args:
model_name: Name of the model.
Returns:
Model parameters.
Model hyperparameters' dict.
"""
# Get directories
save_dir = os.path.join(_get_dir(), model_name)
params_save_dir = os.path.join(save_dir, "ckpt.joblib")
hyperparams_save_dir = os.path.join(save_dir, "hyperparams.json")
if os.path.exists(hyperparams_save_dir) and os.path.exists(params_save_dir):
# Load locally
with open(hyperparams_save_dir, "rb") as f:
hyperparams = json.load(f)
with open(params_save_dir, "rb") as f:
params = joblib.load(f)
return params, hyperparams
else:
os.makedirs(save_dir, exist_ok=True)
s3_endpoint = "https://s3.kao-prod.instadeep.io"
session = boto3.Session()
s3_client = session.client(
service_name="s3",
endpoint_url=s3_endpoint,
config=Config(signature_version=UNSIGNED),
)
# Download params and hyperparams
bucket = "nucleotide-transformer"
download_from_s3_bucket(
s3_client=s3_client,
bucket=bucket,
key=f"checkpoints/{model_name}/hyperparams.json",
filename=hyperparams_save_dir,
)
download_from_s3_bucket(
s3_client=s3_client,
bucket=bucket,
key=f"checkpoints/{model_name}/ckpt.joblib",
filename=params_save_dir,
)
# Load locally
with open(hyperparams_save_dir, "rb") as f:
hyperparams = json.load(f)
with open(params_save_dir, "rb") as f:
params = joblib.load(f)
return params, hyperparams
def get_pretrained_model(
model_name: str,
mixed_precision: bool = False,
embeddings_layers_to_save: Tuple[int, ...] = (),
attention_maps_to_save: Optional[Tuple[Tuple[int, int], ...]] = None,
max_positions: int = 1024,
) -> Tuple[
hk.Params, Callable, FixedSizeNucleotidesKmersTokenizer, NucleotideTransformerConfig
]:
"""
Create a Haiku Nucleotide Transformer
model by downloading pre-trained weights and hyperparameters.
Nucleotide Transformer Models have ESM-like architectures.
Args:
model_name: Name of the model.
mixed_precision: Whether to use mixed precision.
embeddings_layers_to_save: Intermediate embeddings to return in the output.
attention_maps_to_save: Intermediate attention maps to return in the output.
max_positions: Maximum length of a token (for padding).
Returns:
Model parameters.
Haiku function to call the model.
Tokenizer.
Model config (hyperparameters).
Example:
parameters, forward_fn, tokenizer, config = get_pretrained_model(
model_name="500M_1000G",
mixed_precision=False,
# Get embedding at layers 5 and 20
embeddings_layers_to_save=(5, 20,),
# Get attention map number 4 at layer 1 and attention map number 14
# at layer 12
attention_maps_to_save=((1,4), (12, 14)),
max_positions=128,
)
"""
if attention_maps_to_save is None:
attention_maps_to_save = ()
supported_models = [
"500M_human_ref",
"500M_1000G",
"2B5_1000G",
"2B5_multi_species",
]
if not (model_name in supported_models):
raise NotImplementedError(
f"Unknown {model_name} model. " f"Supported models are {supported_models}"
)
# Download weights and hyperparams
parameters, hyperparams = download_ckpt_and_hyperparams(model_name)
tokenizer = FixedSizeNucleotidesKmersTokenizer(
k_mers=hyperparams["k_for_kmers"],
fixed_length=max_positions,
prepend_cls_token=True,
)
# Get config
config = NucleotideTransformerConfig(
alphabet_size=len(tokenizer.vocabulary) - 2,
pad_token_id=tokenizer.pad_token_id,
mask_token_id=tokenizer.mask_token_id,
max_positions=hyperparams["max_positions"],
embed_scale=hyperparams["embed_scale"],
# architecture
emb_layer_norm_before=hyperparams["emb_layer_norm_before"],
key_size=hyperparams["key_dim"] if "key_dim" in hyperparams.keys() else None,
attention_heads=hyperparams["attention_heads"],
embed_dim=hyperparams["embed_dim"],
ffn_embed_dim=hyperparams["ffn_embed_dim"],
num_layers=hyperparams["num_layers"],
# bert
token_dropout=hyperparams["token_dropout"],
masking_ratio=hyperparams["masking_ratio"],
masking_prob=hyperparams["masking_prob"],
# embeddings to save
embeddings_layers_to_save=embeddings_layers_to_save,
attention_maps_to_save=attention_maps_to_save,
)
# NOTE: module names are changed here, to validate !
full_model_name = "nucleotide_transformer" + model_name
parameters = rename_modules(parameters, full_model_name)
forward_fn = build_nucleotide_transformer_fn(
model_config=config, mixed_precision=mixed_precision, model_name=full_model_name
)
return parameters, forward_fn, tokenizer, config
def rename_modules(parameters: hk.Params, model_name: str) -> hk.Params:
"""
Adjusts the names of the modules from checkpoints to NucleotideTransformer.
Args:
parameters: Parameters loaded from .joblib archive.
model_name: Name of the loaded model.
Returns:
Parameters with updated names.
"""
for layer_name in list(parameters.keys()):
new_name = layer_name.replace("esm_transformer", model_name)
if "attention_layer" in new_name:
if new_name.split("/")[3] == "mha":
new_name = "/".join(
new_name.split("/")[:3]
+ ["self_attention"]
+ new_name.split("/")[4:]
)
if "mha_layer_norm" in new_name:
new_name = new_name.replace("mha_layer_norm", "self_attention_layer_norm")
if "esm_roberta_lm_head" in new_name:
new_name = new_name.replace("esm_roberta_lm_head", "roberta_lm_head")
parameters[new_name] = parameters.pop(layer_name)
return parameters
| nucleotide-transformer-main | nucleotide_transformer/pretrained.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
NUCLEOTIDES = ["A", "T", "C", "G"]
VALID_EXTRA_NUCLEOTIDES = ["N", "M", "Y", "B", "S", "W", "K", "H", "D", "V", "R"]
EXTRA_NUCLEOTIDES = ["N"]
| nucleotide-transformer-main | nucleotide_transformer/constants.py |
nucleotide-transformer-main | nucleotide_transformer/__init__.py |
|
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Dict
import jax.numpy as jnp
from typing_extensions import TypeAlias
Embedding: TypeAlias = jnp.ndarray
Tokens: TypeAlias = jnp.ndarray
AttentionMask: TypeAlias = jnp.ndarray
TransformerOutput: TypeAlias = Dict[str, jnp.ndarray] # type: ignore
| nucleotide-transformer-main | nucleotide_transformer/types.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of the Nucleotide Transformer model in Jax."""
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Tuple
import haiku as hk
import jax.numpy as jnp
import jmp
from nucleotide_transformer.layers import (
ESMLearnedPositionalEmbeddings,
RobertaLMHead,
SelfAttentionBlock,
TokensDropout,
)
from nucleotide_transformer.types import (
AttentionMask,
Embedding,
Tokens,
TransformerOutput,
)
def build_padding_attention_mask(tokens: Tokens, pad_token_id: int) -> AttentionMask:
"""
Builds a padding mask from a sequence of tokens by masking <pad> in the attention.
Args:
tokens: Batch of sequences of shape (batch_size, seq_len).
pad_token_id: Int corresponding to the <pad> token to mask.
Returns:
Batch of attention masks, masking out <pad> tokens.
"""
padding_mask = tokens != pad_token_id
padding_mask = padding_mask[:, None, :]
padding_mask = jnp.einsum("bhT, bht->bhtT", padding_mask, padding_mask)
return padding_mask
@dataclass
class NucleotideTransformerConfig:
"""
Parameters to initialize a Nucleotide Transformer model.
Args:
alphabet_size: Token vocabulary.
pad_token_id: ID of pad token.
mask_token_id: ID of mask token.
max_positions: Maximum sequence length.
embed_scale: Correction ratio applied to the embeddings to make up for the
norm difference between the input during training and inference.
emb_layer_norm_before: Whether to use layer norm before the first attention
layer.
attention_heads: Number of attention heads.
key_size: The dimension of the query, key, and values within each attention
head, if not specified, it is set to attention_heads//embed_dim.
It can be useful to set a custom key size if we want to impose the size of
the query, key and value tensor ( for example, tensors shaped with
power of 2 are more efficiently handled on TPUs ).
Note: Parametrizing the model with a custom key size has been done in :
Brown, Tom, et al. "Language models are few-shot learners."
Advances in neural information processing systems 33 (2020): 1877-1901.
embed_dim: Embedding dimension.
ffn_embed_dim: Feed forward embedding dimension.
num_layers: Number of attention blocks.
token_dropout: Token dropout.
masking_ratio: Masking ratio (used if token dropout is enabled).
masking_prob: Masking probability (used if token dropout is enabled).
use_gradient_checkpointing: Whether to use gradient checkpointing (checkpoint
gradients in the forward pass to reduce the computation in the backward).
"""
alphabet_size: int
pad_token_id: int
mask_token_id: int
max_positions: int = 1000
embed_scale: float = 1.0
# architecture
emb_layer_norm_before: bool = False
attention_heads: int = 20
key_size: Optional[int] = None
embed_dim: int = 1280
ffn_embed_dim: int = 5120
num_layers: int = 24
# dropout
token_dropout: bool = False
masking_ratio: float = 0.1
masking_prob: float = 0.8
# logging
use_gradient_checkpointing: bool = False
# return
embeddings_layers_to_save: Tuple[int, ...] = ()
attention_maps_to_save: Tuple[Tuple[int, int], ...] = ()
def __post_init__(self) -> None:
"""
Checks that the given values are compatible.
"""
if self.key_size is None:
if not self.embed_dim % self.attention_heads == 0:
raise ValueError(
f"When no key size is provided, the embedding dimension should be "
f"divisible by the number of heads, however provided embedding "
f"dimension is {self.embed_dim} and the number of heads is "
f"{self.attention_heads}."
)
self.key_size = self.embed_dim // self.attention_heads
class NucleotideTransformer(hk.Module):
"""
Jax implementation of Nucleotide Transformer models.
"""
def __init__(
self,
config: NucleotideTransformerConfig,
name: Optional[str] = None,
):
"""
Initialize a Nucleotide Transformer model.
Args:
config: Dataclass containing model hyperparameters.
name: Name for module (custom will break weight loading).
"""
self._config = config
super().__init__(name=name)
self._embed_layer = hk.Embed(self._config.alphabet_size, self._config.embed_dim)
self._pos_embed_layer = ESMLearnedPositionalEmbeddings(
config.max_positions, config.embed_dim, config.pad_token_id
)
self._lm_head = RobertaLMHead(
embed_dim=self._config.embed_dim,
alphabet_size=self._config.alphabet_size,
name="roberta_lm_head",
)
if self._config.emb_layer_norm_before:
self.emb_ln_before = hk.LayerNorm(
axis=-1,
create_scale=True,
create_offset=True,
name="emb_layer_norm_before",
)
# Process attention maps to save requirement into more suitable format
attention_maps_to_save = config.attention_maps_to_save
self._attention_layers_to_save = list({t[0] for t in attention_maps_to_save})
self._attention_maps_per_layer_to_save = {
layer: [t[1] for t in attention_maps_to_save if t[0] == layer]
for layer in self._attention_layers_to_save
}
# Checking user request can be executed, raise error otherwise
max_layer = max(self._attention_layers_to_save + [0])
if max_layer > config.num_layers:
raise ValueError(
f"You are requiring attention maps for layer {max_layer}, "
f"while the model has {config.num_layers} layers only."
)
for layer, maps in self._attention_maps_per_layer_to_save.items():
max_map = max(maps)
if max_map > config.attention_heads:
raise ValueError(
f"You are requiring attention maps number {max_map} "
f"at layer {layer}, while the model has {config.attention_heads} "
f"only."
)
@hk.transparent
def apply_attention_blocks(
self,
x: Embedding,
outs: Dict[str, Embedding],
attention_mask: Optional[AttentionMask] = None,
) -> Tuple[Embedding, Dict[str, Embedding]]:
"""
Create the blocks of attention layers and applies them.
Args:
x: The sequence embedding.
outs: A dictionary to carry through the attention layers which stores the
intermediate sequence embedding and attention maps.
attention_mask: Attention mask of shape (batch_size, 1, seq_len, seq_len).
Returns:
The output sequence embedding.
The optional intermediate results (embeddings of the layer and attention
weights).
"""
layers: List[Callable] = [
self._attention_block(layer_idx)
for layer_idx in range(self._config.num_layers)
]
if self._config.use_gradient_checkpointing:
# the remat-ed function cannot take control flow arguments
layers = [hk.remat(layer) for layer in layers]
for layer_idx, layer in enumerate(layers):
output = layer(
x=x,
attention_mask=attention_mask,
)
x = output["embeddings"]
# Save intermediate embeddings if needed
if (layer_idx + 1) in self._config.embeddings_layers_to_save:
outs[f"embeddings_{(layer_idx+1)}"] = output["embeddings"]
# Save intermediate attention maps if needed
if (layer_idx + 1) in self._attention_layers_to_save:
for map_number in self._attention_maps_per_layer_to_save[layer_idx + 1]:
dkey = f"attention_map_layer_{layer_idx + 1}_number_{map_number}"
outs[dkey] = output["attention_weights"][:, map_number + 1]
return x, outs
@hk.transparent
def _attention_block(self, layer_idx: int) -> SelfAttentionBlock:
return SelfAttentionBlock( # type: ignore
num_heads=self._config.attention_heads,
embed_dim=self._config.embed_dim,
key_size=self._config.key_size,
ffn_embed_dim=self._config.ffn_embed_dim,
name=f"attention_layer_{layer_idx}",
)
def __call__(
self,
tokens: Tokens,
attention_mask: Optional[AttentionMask] = None,
) -> TransformerOutput:
"""
Computes the embeddings based on the input tokens.
Args:
tokens: Input tokens out of the tokenizer of shape (batch_size, seq_len).
attention_mask: Attention mask of shape (batch_size, 1, seq_len, seq_len).
If no mask is provided, a mask by default which equals 1 over all non
pad tokens and 0 over pad tokens is computed.
Returns:
Dictionary containing the final embeddings and logits.
"""
# Prepare outputs dict
outs: Dict[str, jnp.ndarray] = {}
# Compute embeddings
x = self._embed_layer(tokens)
# Tokens dropout if needed
if self._config.token_dropout:
x = TokensDropout(
embed_dim=self._config.embed_dim,
mask_token_id=self._config.mask_token_id,
pad_token_id=self._config.pad_token_id,
masking_ratio=self._config.masking_ratio,
masking_prob=self._config.masking_prob,
)(x, tokens)
# RoBERTa's mask scaling factor
x = self._config.embed_scale * x
# Add check that the sequence fed into the transformer is not longer
# than the max positions used to instantiate the learned positional
# embeddings layer
assert tokens.shape[1] <= self._config.max_positions, (
"Inputs to the learned positional embeddings layer have a length "
f"{x.shape[1]} greater than the max positions used to instantiate "
f"it: {self._config.max_positions}"
)
# Positional Embedding
x = x + self._pos_embed_layer(tokens)
if self._config.emb_layer_norm_before:
x = self.emb_ln_before(x)
# Attention mask
if attention_mask is None:
attention_mask = build_padding_attention_mask(
tokens=tokens, pad_token_id=self._config.pad_token_id
)
# construct a tower of attention layers
x, outs = self.apply_attention_blocks(
x=x,
outs=outs,
attention_mask=attention_mask,
)
# Language Model Head
lm_head_outs = self._lm_head(x)
outs["logits"] = lm_head_outs["logits"]
embeddings = lm_head_outs["embeddings"]
# Save final embeddings if needed
if self._config.num_layers in self._config.embeddings_layers_to_save:
outs[f"embeddings_{self._config.num_layers}"] = embeddings
return outs # type: ignore
def build_nucleotide_transformer_fn(
model_config: NucleotideTransformerConfig,
mixed_precision: bool = False,
model_name: Optional[str] = None,
) -> Callable:
"""
Creates the model's forward pass.
Args:
model_config: Model hyperparameters.
mixed_precision: Whether to use mixed precision computation.
model_name: Model's name.
Returns:
Nucleotide Transformer model forward function.
"""
if mixed_precision:
# Use mixed precision (only support A100 GPU and TPU for now)
half = jnp.bfloat16
full = jnp.float32
policy = jmp.Policy(compute_dtype=half, param_dtype=full, output_dtype=full)
hk.mixed_precision.set_policy(NucleotideTransformer, policy)
# Remove it in batch norm to avoid instabilities
policy = jmp.Policy(compute_dtype=full, param_dtype=full, output_dtype=half)
hk.mixed_precision.set_policy(hk.BatchNorm, policy)
hk.mixed_precision.set_policy(hk.LayerNorm, policy)
def nucleotide_transformer_fn(
tokens: Tokens, attention_mask: Optional[AttentionMask] = None
) -> TransformerOutput:
"""Forward pass."""
# Run the encoder over the inputs.
encoder = NucleotideTransformer(config=model_config, name=model_name)
outs = encoder(
tokens=tokens,
attention_mask=attention_mask,
)
return outs
return nucleotide_transformer_fn
| nucleotide-transformer-main | nucleotide_transformer/model.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Dict, Optional
import haiku as hk
import jax
import jax.numpy as jnp
from haiku import initializers
from nucleotide_transformer.types import (
AttentionMask,
Embedding,
Tokens,
TransformerOutput,
)
class MultiHeadAttention(hk.MultiHeadAttention):
"""
Multi-head attention with masking applied. Modified from the core implementation to
support biases in keys and values.
"""
def __init__(
self,
num_heads: int,
key_size: int,
value_size: Optional[int] = None,
model_size: Optional[int] = None,
name: Optional[str] = None,
):
"""
Args:
num_heads: Number of independent attention heads.
key_size: The size of keys and queries used for attention.
value_size: Optional size of the value projection. If None, defaults
to the key size.
model_size: Optional size of the output embedding. If None, defaults
to the key size multiplied by the number of heads.
name: Optional name for this module.
"""
w_init = hk.initializers.VarianceScaling(2.0, "fan_in", "uniform")
super().__init__(
num_heads=num_heads,
key_size=key_size,
w_init=w_init,
value_size=value_size,
model_size=model_size,
name=name,
)
@hk.transparent
def attention_weights(
self,
query: jnp.ndarray,
key: jnp.ndarray,
attention_mask: Optional[AttentionMask] = None,
) -> jnp.ndarray:
"""
Computes the attention weights.
Args:
query: Embedding sequence to compute queries.
key: Embedding sequence to compute keys.
attention_mask: Input attention_mask. Defaults to None.
Returns:
Attention weights.
"""
query_heads = self._linear_projection_he_init(query, self.key_size, "query")
key_heads = self._linear_projection_he_init(key, self.key_size, "key")
attention_logits = jnp.einsum("...thd,...Thd->...htT", query_heads, key_heads)
sqrt_key_size = jnp.sqrt(self.key_size).astype(query.dtype)
attention_logits = attention_logits / sqrt_key_size
if attention_mask is not None:
assert len(attention_mask.shape) == len(attention_logits.shape)
attention_logits = jnp.where(attention_mask, attention_logits, -1e30)
attention_weights = jax.nn.softmax(attention_logits)
return attention_weights
@hk.transparent
def compute_embeddings(
self,
value: jnp.ndarray,
attention_weights: jnp.ndarray,
) -> jnp.ndarray:
"""
Computes the output embeddings.
Args:
value: Embedding sequence to compute values.
attention_weights: Attention weights.
Returns:
Output embeddings.
"""
# He initialization
w_init = initializers.VarianceScaling(2.0, "fan_in", "uniform")
b_init = initializers.VarianceScaling(2.0, "fan_in", "uniform")
value_heads = self._linear_projection_he_init(value, self.value_size, "value")
attention = jnp.einsum("...htT,...Thd->...thd", attention_weights, value_heads)
# Concatenate attention matrix of all heads into a single vector.
attention_vec = jnp.reshape(attention, (*value.shape[:-1], -1))
return hk.Linear(
self.model_size, w_init=w_init, b_init=b_init, name="mha_output"
)(attention_vec)
def __call__(
self,
query: jnp.ndarray,
key: jnp.ndarray,
value: jnp.ndarray,
attention_mask: Optional[jnp.ndarray] = None,
) -> TransformerOutput:
"""
Computes both the embeddings and the attention weights.
Args:
query: Embedding sequence to compute queries.
key: Embedding sequence to compute keys.
value: Embedding sequence to compute values.
attention_mask: Mask to be applied during the attention layers.
Triangular for autoregressive models. Defaults to None.
Returns:
Dictionary containing the output embeddings and the attention weights.
"""
attention_weights = self.attention_weights(query, key, attention_mask)
embeddings = self.compute_embeddings(value, attention_weights)
return {"embeddings": embeddings, "attention_weights": attention_weights}
@hk.transparent
def _linear_projection_he_init(
self, x: jnp.ndarray, head_size: int, name: Optional[str] = None
) -> jnp.ndarray:
"""
Linear layer for multi-head attention mechanism. Initialized with the He method.
Args:
x: Input embeddings.
head_size: Embedding size of each attention head.
name: Name of the linear layer.
Returns:
Multi-head embeddings.
"""
# He initialization
w_init = initializers.VarianceScaling(2.0, "fan_in", "uniform")
b_init = initializers.VarianceScaling(2.0, "fan_in", "uniform")
y = hk.Linear(
self.num_heads * head_size, w_init=w_init, b_init=b_init, name=name
)(x)
return y.reshape((*x.shape[:-1], self.num_heads, head_size))
class SelfAttentionBlock(hk.Module):
"""
Attention block made of self-attention.
"""
def __init__(
self,
num_heads: int,
embed_dim: int,
ffn_embed_dim: int,
key_size: Optional[int] = None,
name: Optional[str] = None,
):
super().__init__(name=name)
# Add checks on dimensions
if key_size is None:
if embed_dim % num_heads != 0:
raise ValueError(
f"The embedding dimension should be divisible by the number of "
f"heads, however provided embedding dimension is {embed_dim} and "
f"the number of heads is {num_heads}."
)
key_size = embed_dim // num_heads
# Define layers
self.fc1 = hk.Linear(ffn_embed_dim, name="fc1")
self.fc2 = hk.Linear(embed_dim, name="fc2")
self.layer_norm_self_attention = hk.LayerNorm(
axis=-1,
create_scale=True,
create_offset=True,
name="self_attention_layer_norm",
)
self.layer_norm_mlp = hk.LayerNorm(
axis=-1, create_scale=True, create_offset=True, name="final_layer_norm"
)
self.sa_layer = MultiHeadAttention(
num_heads=num_heads,
key_size=key_size,
model_size=embed_dim,
name="self_attention",
)
@hk.transparent
def self_attention(
self,
x: Embedding,
attention_mask: Optional[AttentionMask] = None,
) -> TransformerOutput:
"""
Applies the self attention mechanism.
Args:
x: Input token embeddings of shape (batch_size, seq_len, embed_dim).
attention_mask: Attention mask of shape (batch_size, 1, seq_len, seq_len).
Returns:
Dictionary containing the output embeddings and the attention weights.
"""
return self.sa_layer(x, x, x, attention_mask=attention_mask)
@hk.transparent
def mlp(self, x: Embedding) -> Embedding:
"""
Applies one layer-norm, one linear layer, a Gelu activation,
then a final linear layer.
Args:
x: Embeddings of shape (batch_size, seq_len, key_size * num_heads).
Returns:
The transformed sequence embedding.
"""
x = self.layer_norm_mlp(x)
x = jax.nn.gelu(
self.fc1(x),
approximate=False,
)
x = self.fc2(x)
return x
def __call__(
self,
x: Tokens,
attention_mask: Optional[AttentionMask] = None,
) -> TransformerOutput:
"""
Computes the output of the attention layer.
Args:
x: Input token embeddings of shape (batch_size,seq_len,embed_dim).
attention_mask: Attention mask of shape (batch_size, 1,seq_len, seq_len).
Returns:
A dictionary containing the output embeddings and the attention weights.
"""
# Self-Attention
res = x
x = self.layer_norm_self_attention(x)
output = self.self_attention(
x=x,
attention_mask=attention_mask,
)
x = output["embeddings"]
x = res + x
# MLP
x = x + self.mlp(x)
output["embeddings"] = x
return output # type: ignore
class RobertaLMHead(hk.Module):
"""
Roberta Language Model head. Transform final attention layer output into a
distribution over tokens at each position.
"""
def __init__(self, embed_dim: int, alphabet_size: int, name: Optional[str] = None):
"""
Args:
embed_dim: Embedding dimension.
alphabet_size: Number of tokens in the alphabet.
name: Name of the layer. Defaults to None.
"""
super().__init__(name=name)
self.embed_dim = embed_dim
self.alphabet_size = alphabet_size
# Define layers
self._first_layer_norm = hk.LayerNorm(
axis=-1, create_scale=True, create_offset=True, name="emb_layer_norm_after"
)
self._fc1 = hk.Linear(self.embed_dim, name="lm_head_fc_1")
self._final_fc = hk.Linear(self.alphabet_size, name="lm_final_fc")
self._second_layer_norm = hk.LayerNorm(
axis=-1, create_scale=True, create_offset=True, name="lm_head_layer_norm"
)
def __call__(self, x: jnp.ndarray) -> Dict[str, jnp.ndarray]:
x = self._first_layer_norm(x)
# Embeddings are computed after the first layer norm to be consistent with ESM
embeddings = x
x = self._fc1(x)
x = jax.nn.gelu(x, approximate=False)
x = self._second_layer_norm(x)
# Compute logits
logits = self._final_fc(x)
return {"embeddings": embeddings, "logits": logits}
class TokensDropout(hk.Module):
"""
Tokens dropout layer.
"""
def __init__(
self,
embed_dim: int,
pad_token_id: int,
mask_token_id: int,
masking_ratio: float,
masking_prob: float,
name: Optional[str] = None,
):
"""
Args:
embed_dim: Embedding dimension.
pad_token_id: ID of the pad token.
mask_token_id: ID of the pad token.
masking_ratio: Masking ratio.
masking_prob: Probability to mask.
name: Name of the layer. Defaults to None.
"""
super().__init__(name=name)
self.pad_token_id = pad_token_id
self.mask_token_id = mask_token_id
self.masking_ratio = masking_ratio
self.masking_prob = masking_prob
self.embed_dim = embed_dim
def __call__(self, x: jnp.ndarray, tokens: Tokens) -> jnp.ndarray:
padding_mask_tokens = tokens == self.pad_token_id
tokens_repeated = jnp.repeat(
tokens[:, :, None], repeats=self.embed_dim, axis=-1
)
x = jnp.where(tokens_repeated == self.mask_token_id, 0.0, x)
mask_ratio_train = self.masking_ratio * self.masking_prob
src_lengths = (~padding_mask_tokens).sum(-1)
mask_ratio_observed = (tokens == self.mask_token_id).sum(-1) / src_lengths
x = x * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]
return x
class ESMLearnedPositionalEmbeddings(hk.Module):
"""
Learned positional embeddings to be added to token embeddings. Specific to ESM as it
is implemented by shifting the positions by 2 (1 + padding_idx).
"""
def __init__(
self,
vocab_size: int,
embed_dim: int,
padding_idx: int,
name: Optional[str] = None,
):
"""
Args:
vocab_size: Tokenizer's vocabulary size.
embed_dim: Embedding size.
padding_idx: Index attributed to the padding
token. Defaults to 1.
name: Name of the layer. Defaults to None.
"""
super().__init__(name=name)
self.padding_idx = padding_idx
self._embed_layer = hk.Embed(vocab_size + padding_idx + 1, embed_dim)
def __call__(self, tokens: jnp.ndarray) -> jnp.ndarray:
mask = tokens != self.padding_idx
positions = jnp.cumsum(mask, axis=1) * mask + self.padding_idx
return self._embed_layer(positions)
| nucleotide-transformer-main | nucleotide_transformer/layers.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from itertools import product
from typing import Dict, List, Optional, Tuple
import numpy as np
import regex as re
from nucleotide_transformer.constants import EXTRA_NUCLEOTIDES, NUCLEOTIDES
def _compute_k_mers(k: int) -> List[str]:
"""
Generates all the different k-mers for nucleotides given a value of k.
Args:
k: The k parameter for k-mers.
Returns:
All the different k-mers.
"""
return ["".join(elt) for elt in product(NUCLEOTIDES, repeat=k)]
class StandardTokenizer:
"""
Simple tokenizer that extracts pre-defined tokens from sequences using regex.
"""
def __init__(
self,
standard_tokens: List[str],
unk_token: str = "<unk>",
pad_token: str = "<pad>",
mask_token: str = "<mask>",
class_token: str = "<cls>",
eos_token: str = "<eos>",
bos_token: str = "<bos>",
prepend_bos_token: bool = False,
prepend_cls_token: bool = False,
append_eos_token: bool = False,
extra_special_tokens: Optional[List[str]] = None,
tokens_to_ids: Optional[Dict[str, int]] = None,
):
"""
Initializes a basic tokenizer instance.
Args:
standard_tokens: Standard tokens, where special tokens are omitted.
unk_token: Unknown token.
pad_token: Pad token.
mask_token: Mask token.
class_token: Class token.
eos_token: End of speech tokens.
bos_token: Beginning of sentence token.
prepend_bos_token: Prepend beginning of sentence token.
prepend_cls_token: Prepend class token.
append_eos_token: Append end of speech token.
extra_special_tokens: (Optional) Enable the user to define optionally
additional special tokens. Since regex is used for tokenization, any
special tokens that are also special tokens in regex must include
a "\" escape seq. For instance "$" -> "\\$"
tokens_to_ids: (Optional) Enable the user to optionally choose ids for
the tokens. If you provide this argument the dictionary must include
the following special tokens
["<unk>","<pad>","<mask>","<cls>","<eos>","<bos>"]
or instantiation will fail. Additionally, if the ids in your dictionary
do not start at 0 then an error will also be raised. If this argument is
not specified, then ids are attributed automatically by the tokenizer
during initialization.
"""
# Define special tokens essential to masked language modelling
special_tokens_1 = [unk_token, pad_token, mask_token, class_token]
special_tokens_2 = [eos_token, bos_token]
special_tokens = special_tokens_1 + special_tokens_2
all_tokens = special_tokens_1 + standard_tokens + special_tokens_2
if extra_special_tokens is not None:
special_tokens.extend(extra_special_tokens)
self._all_tokens = all_tokens
self._standard_tokens = standard_tokens
self._special_tokens = special_tokens
self._unk_token = unk_token
self._pad_token = pad_token
self._mask_token = mask_token
self._class_token = class_token
self._eos_token = eos_token
self._bos_token = bos_token
self._prepend_bos_token = prepend_bos_token
self._prepend_cls_token = prepend_cls_token
self._append_eos_token = append_eos_token
# Can only
if self._prepend_bos_token and self._prepend_cls_token:
raise ValueError(
"Cannot prepend both BOS and CLS token, must choose only one"
)
# Matching between tokens and ids
if tokens_to_ids is not None:
if set(tokens_to_ids.keys()) != set(self._all_tokens):
raise ValueError(
f"Specified matching between tokens and ids, "
f"but some tokens are missing or mismatch. "
f"Got specifications for tokens: {set(tokens_to_ids.keys())} "
f"and expected for {set(self._all_tokens)}"
)
sorted_tokens = np.sort(list(tokens_to_ids.values()))
if np.any(sorted_tokens != np.arange(len(self._all_tokens))):
raise ValueError(
f"Specified matching between tokens and ids, "
f"but some ids are missing or mismatch. "
f"Got specifications for ids: {sorted_tokens} "
f"and expected for {np.arange(len(self._all_tokens))}"
)
self._tokens_to_ids = tokens_to_ids
else:
self._tokens_to_ids = {tok: i for i, tok in enumerate(self._all_tokens)}
self._ids_to_tokens = {i: tok for tok, i in self._tokens_to_ids.items()}
self._compiled_regex = re.compile("|".join(self._all_tokens + [r"\S"])) # noqa
@property
def vocabulary(self) -> List[str]:
return self._all_tokens
@property
def standard_tokens(self) -> List[str]:
return self._standard_tokens
@property
def vocabulary_size(self) -> int:
"""
Property that returns the total number of tokens.
Returns:
Total number of tokens.
"""
return len(self.vocabulary)
@property
def unk_token_id(self) -> int:
"""
Property that returns id (int representation) of the unknown token.
Returns:
Id (int representation) of the unknown token.
"""
return self.token_to_id(self.unk_token)
@property
def pad_token_id(self) -> int:
"""
Property that returns id (int representation) of the pad token.
Returns:
Id (int representation) of the pad token.
"""
return self.token_to_id(self.pad_token)
@property
def mask_token_id(self) -> int:
"""
Property that returns id (int representation) of the mask token.
Returns:
Id (int representation) of the mask token.
"""
return self.token_to_id(self.mask_token)
@property
def class_token_id(self) -> int:
"""
Property that returns id (int representation) of the class token.
Returns:
Id (int representation) of the class token.
"""
return self.token_to_id(self.class_token)
@property
def eos_token_id(self) -> int:
"""
Property that returns id (int representation) of the eos token.
Returns:
Id (int representation) of the eos token.
"""
return self.token_to_id(self.eos_token)
@property
def bos_token_id(self) -> int:
"""
Property that returns id (int representation) of the bos token.
Returns:
Id (int representation) of the bos token.
"""
return self.token_to_id(self.bos_token)
@property
def special_tokens(self) -> List[str]:
return self._special_tokens
@property
def unk_token(self) -> str:
return self._unk_token
@property
def pad_token(self) -> str:
return self._pad_token
@property
def mask_token(self) -> str:
return self._mask_token
@property
def class_token(self) -> str:
return self._class_token
@property
def eos_token(self) -> str:
return self._eos_token
@property
def bos_token(self) -> str:
return self._bos_token
def id_to_token(self, token_id: int) -> str:
try:
return self._ids_to_tokens[token_id]
except KeyError:
raise KeyError(f"Token id {token_id} not found in vocabulary")
def token_to_id(self, token: str) -> int:
try:
return self._tokens_to_ids[token]
except KeyError:
raise KeyError(f"Token {token} not found in vocabulary")
def tokenize(self, sequence: str) -> Tuple[List[str], List[int]]:
"""
Tokenizes a sequence and returns the list of tokens as well
as the list of their IDs. Any character found in the sequence that does not
correspond to any token in the vocabulary is replaced by the unk token.
Args:
sequence: Sequence to be tokenized.
Returns:
List of tokens.
List of token ids.
"""
tokens: List[str] = self._compiled_regex.findall(sequence)
tokens = [
tok if tok in self._tokens_to_ids.keys() else self._unk_token
for tok in tokens
]
if self._prepend_cls_token:
tokens = [self._class_token] + tokens
if self._prepend_bos_token:
tokens = [self._bos_token] + tokens
if self._append_eos_token:
tokens.append(self._eos_token)
tokens_ids = [self.token_to_id(tok) for tok in tokens]
return tokens, tokens_ids
def pad_tokens_batch(
self, batch: List[Tuple[List[str], List[int]]]
) -> List[Tuple[List[str], List[int]]]:
"""
Takes a batch of sequences tokens ids and returns a batch of padded sequences.
Args:
batch: List of tuples, each composed of a sequence's tokens and token ids.
Returns:
List of 2-elements tuple for each sequence in the input where the tuple is
containing 1. the list of the str representations of the
tokens for that sequence and 2. the list of the int representations of
the tokens for that sequence. Pad Tokens are added so that each sequence
of tokens in the batch has the same length (all sequences padded to the
length of the longest sequence in the batch).
"""
lengths = [len(t[0]) for t in batch]
maximum_length = max(lengths)
deltas = [maximum_length - length for length in lengths]
padded_tokens = [
t[0] + ([self.pad_token] * delta) for t, delta in zip(batch, deltas)
]
padded_tokens_ids = [
t[1] + ([self.pad_token_id] * delta) for t, delta in zip(batch, deltas)
]
return [
(toks, toks_ids) for toks, toks_ids in zip(padded_tokens, padded_tokens_ids)
]
def batch_tokenize(self, sequences: List[str]) -> List[Tuple[List[str], List[int]]]:
"""
Tokenizes a batch of sequences.
Sequences are padded to the maximum length in the batch.
Args:
sequences: Batch of sequences to be tokenized.
Returns:
Batch of tokenized sequences as well as their token ids,
where every sequence has been padded to the maximum length
in the batch.
"""
return self.pad_tokens_batch( # type: ignore
[self.tokenize(seq) for seq in sequences]
)
class NucleotidesKmersTokenizer(StandardTokenizer):
"""
This is a tokenizer specific for nucleotide sequences.
It only considers sequence containing the tokens A, T, C, G and N.
N is always considered as a special token and tokenized alone.
"""
def __init__(
self,
k_mers: int,
unk_token: str = "<unk>",
pad_token: str = "<pad>",
mask_token: str = "<mask>",
class_token: str = "<cls>",
eos_token: str = "<eos>",
bos_token: str = "<bos>",
prepend_bos_token: bool = False,
prepend_cls_token: bool = False,
append_eos_token: bool = False,
tokens_to_ids: Optional[Dict[str, int]] = None,
):
"""
Instantiates a FixedSizeNucleotideKmersTokenizer.
Args:
k_mers: How many nucleotides to consider for generating vocabulary.
unk_token: Unknown token.
pad_token: Pad token.
mask_token: Mask token.
class_token: Class token.
eos_token: End of speech tokens.
bos_token: Beginning of sentence token.
prepend_bos_token: Prepend beginning of sentence token.
prepend_cls_token: Prepend class token.
append_eos_token: Append end of speech token.
tokens_to_ids: (Optional) Enable the user to optionally choose ids for
the tokens. If you provide this argument the dictionary must include
the following special tokens
["<unk>","<pad>","<mask>","<cls>","<eos>","<bos>"]
or instantiation will fail. Additionally, if the ids in your dictionary
do not start at 0 then an error will also be raised. If this argument is
not specified, then ids are attributed automatically by the tokenizer
during initialization.
"""
kmers_tokens = _compute_k_mers(k_mers)
standard_tokens = kmers_tokens + NUCLEOTIDES + EXTRA_NUCLEOTIDES
StandardTokenizer.__init__(
self,
standard_tokens=standard_tokens,
unk_token=unk_token,
pad_token=pad_token,
mask_token=mask_token,
class_token=class_token,
eos_token=eos_token,
bos_token=bos_token,
prepend_bos_token=prepend_bos_token,
prepend_cls_token=prepend_cls_token,
append_eos_token=append_eos_token,
tokens_to_ids=tokens_to_ids,
)
self._k_mers = k_mers
def tokenize(self, sequence: str) -> Tuple[List[str], List[int]]:
"""
Tokenizes a sequence and returns the list of tokens as well
as the list of their IDs. The tokenization algorithm first splits up the
substrings of the input sequence in-between N characters.
Then these substrings are split into pieces of length k, and if it
is possible (edge cases) it adds up pieces of length 1.
If a single character that does not correspond
to any token is found, an error is raised.
Args:
sequence: Sequence to be tokenized.
Returns:
List of tokens.
List of token ids.
Example:
Find below two tokenization examples when k_mers=5.
ATCGAATGGCGATGCAC --> ATCGA ATGGC GATGC A C
ATCGAATNGGCGATGCAC -> ATCGA A T N GGCGA TGCAC
"""
splitted_seq = sequence.split("N")
len_splitted = len(splitted_seq)
tokens: List[str] = []
for i, split in enumerate(splitted_seq):
chunks = [
split[i * self._k_mers : (i + 1) * self._k_mers]
for i in range(len(split) // self._k_mers)
]
if len(split) % self._k_mers != 0:
chunks.append(split[(len(split) // self._k_mers) * self._k_mers :])
for chunk in chunks:
if len(chunk) == self._k_mers:
tokens.append(chunk)
else:
for nucl in chunk:
tokens.append(nucl)
if i < len_splitted - 1:
tokens.append("N")
if self._prepend_cls_token:
tokens = [self._class_token] + tokens
if self._prepend_bos_token:
tokens = [self._bos_token] + tokens
if self._append_eos_token:
tokens.append(self._eos_token)
tokens_ids = [self.token_to_id(tok) for tok in tokens]
return tokens, tokens_ids
class FixedSizeNucleotidesKmersTokenizer(NucleotidesKmersTokenizer):
"""
Simple tokenizer that naively extracts tokens. Used for amino-acids
and nucleotides. This tokenizer also tokenizes batches to a
fixed maximum length. If one of the sequences provided exceeds the maximum
length, an exception is raised.
"""
def __init__(
self,
k_mers: int,
fixed_length: int,
unk_token: str = "<unk>",
pad_token: str = "<pad>",
mask_token: str = "<mask>",
class_token: str = "<cls>",
eos_token: str = "<eos>",
bos_token: str = "<bos>",
prepend_bos_token: bool = False,
prepend_cls_token: bool = False,
append_eos_token: bool = False,
tokens_to_ids: Optional[Dict[str, int]] = None,
):
"""
Instantiates a FixedSizeNucleotideKmersTokenizer.
Args:
k_mers: How many nucleotides to consider for generating vocabulary.
unk_token: Unknown token.
pad_token: Pad token.
mask_token: Mask token.
class_token: Class token.
eos_token: End of speech tokens.
bos_token: Beginning of sentence token.
prepend_bos_token: Prepend beginning of sentence token.
prepend_cls_token: Prepend class token.
append_eos_token: Append end of speech token.
fixed_length: Fixed length to pad all sequences in batches.
"""
NucleotidesKmersTokenizer.__init__(
self,
unk_token=unk_token,
pad_token=pad_token,
mask_token=mask_token,
class_token=class_token,
eos_token=eos_token,
bos_token=bos_token,
prepend_bos_token=prepend_bos_token,
prepend_cls_token=prepend_cls_token,
append_eos_token=append_eos_token,
k_mers=k_mers,
tokens_to_ids=tokens_to_ids,
)
self._fixed_length = fixed_length
@property
def fixed_length(self) -> int:
"""
Property that returns the pre-defined fixed sequence length.
Returns:
The pre-defined fixed sequence length.
"""
return self._fixed_length
def pad_tokens_batch(
self, batch: List[Tuple[List[str], List[int]]]
) -> List[Tuple[List[str], List[int]]]:
"""
Takes tokens and tokens ids of a batch of sequences, and returns a batch of
padded sequences.
Args:
batch: List of tuples, each composed of a sequence's tokens and token ids.
Returns:
The padded list, where every sequence is padded to the fixed maximum length.
"""
lengths = [len(t[0]) for t in batch]
maximum_length = max(lengths)
if maximum_length > self._fixed_length:
raise ValueError(
f"Found a sequence with length {maximum_length} that "
f"exceeds the fixed length to tokenize ({self._fixed_length})."
)
deltas = [self._fixed_length - length for length in lengths]
padded_tokens = [
t[0] + ([self.pad_token] * delta) for t, delta in zip(batch, deltas)
]
padded_tokens_ids = [
t[1] + ([self.pad_token_id] * delta) for t, delta in zip(batch, deltas)
]
return [
(toks, toks_ids) for toks, toks_ids in zip(padded_tokens, padded_tokens_ids)
]
| nucleotide-transformer-main | nucleotide_transformer/tokenizers.py |
from setuptools import setup, find_packages
setup(
name = 'Galvatron',
packages = find_packages(exclude=[]),
version = '0.0.3',
license='MIT',
description = 'Swarms - Pytorch',
author = 'Kye Gomez',
author_email = '[email protected]',
long_description_content_type = 'text/markdown',
url = 'https://github.com/kyegomez/Galvatron',
keywords = [
'artificial intelligence',
'deep learning',
'optimizers',
"Prompt Engineering"
],
install_requires=[
'transformers',
'torch'
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
],
) | Galvatron-master | setup.py |
from Galvatron import GalvatronUltra
galvatronMega = GalvatronUltra(use_4bit_quantization=True)
modality_data = {
"Text": "Text data",
"Image": "examples/100-trillion.png",
# "Audio": "/path/to/audio.mp3",
# "Video": "/path/to/video.mp4", # Uncomment if video data is available
# "Point Cloud": "/path/to/pointcloud.data", # Uncomment if point cloud data is available
}
response = galvatronMega.generate(modality_data)
print(response) | Galvatron-master | examples/test.py |
from Galvatron.model import GalvatronBaseLM, Galvatron, GalvatronMega, GalvatronUltra | Galvatron-master | Galvatron/__init__.py |
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AutoConfig
class GalvatronBaseLM:
"""
This class is designed to initialize the base language model, in this case MosaicML's mpt-30b-chat,
with the option for 4-bit quantization.
It also integrates additional tools and training efficiency features such as FlashAttention, ALiBi, QK LayerNorm, and more.
"""
def __init__(self, model_id: str = 'mosaicml/mpt-30b-chat', use_4bit_quantization: bool = False, quant_config: BitsAndBytesConfig = None):
"""
:param model_id: model identifier used for loading the model from transformers library
:param use_4bit_quantization: flag indicating whether to use 4-bit quantization
:param quant_config: an instance of BitsAndBytesConfig for 4-bit quantization
"""
self.model_id = model_id
self.use_4bit_quantization = use_4bit_quantization
self.quant_config = quant_config if quant_config is not None else self.default_quant_config()
self.tokenizer = AutoTokenizer.from_pretrained(model_id)
config = AutoConfig.from_pretrained(self.model_id, trust_remote_code=True)
config.attn_config['attn_impl'] = 'triton'
config.init_device = 'cuda:0'
if self.use_4bit_quantization:
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, config=config, quantization_config=self.quant_config, torch_dtype=torch.bfloat16, trust_remote_code=True)
else:
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, config=config, trust_remote_code=True)
@staticmethod
def default_quant_config():
"""
Default 4bit quantization configuration.
"""
return BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
def generate(self, text: str, max_new_tokens: int = 100):
"""
Generate a response from the language model.
:param text: input text
:param max_new_tokens: maximum number of new tokens for the generated text
:return: generated text
"""
inputs = self.tokenizer(text, return_tensors="pt").to('cuda:0')
outputs = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
# galvatron = GalvatronBaseLM(use_4bit_quantization=True)
# text="What is your theory of everythibg"
# response = galvatron.generate(text)
# print(response)
from ImageBind.models import imagebind_model
from ImageBind.models.imagebind_model import ModalityType
from ImageBind.data import data
class Galvatron(GalvatronBaseLM):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.imagebind_model = imagebind_model.imagebind_huge(pretrained=True).eval().to("cuda:0")
def embed_multi_modal_inputs(self, text: str, image_path: str = None, audio_path: str = None):
#transform and load data
inputs = {
ModalityType.TEXT: data.load_and_transform_text([text], 'cuda:0')
}
if image_path is not None:
inputs[ModalityType.VISION] = data.load_and_transform_vision_data([image_path], 'cuda:0')
if audio_path is not None:
inputs[ModalityType.AUDIO] = data.load_and_transform_audio_dataset([audio_path], 'cuda:0')
with torch.no_grad():
embeddings = self.imagebind_model(inputs)
return embeddings
def generate(self, text: str, image_path: str = None, audio_path: str = None, max_new_tokens: int = 100):
embeddings = self.embed_multi_modal_inputs(text, image_path, audio_path)
outputs = self.model.generate(embeddings, max_new_tokens=max_new_tokens)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
################# = V3
class GalvatronMega(GalvatronBaseLM):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.imagebind_model = imagebind_model.imagebind_huge(pretrained=True).eval().to('cuda:0')
def embed_multimodal_inputs(self, modality, img_path, img_weight, text_path, text_weight, video_path, video_weight, audio_path, audio_weight, point_path, point_weight):
inputs = {}
if 'Image' in modality:
image = data.load_and_transform_vision_data([img_path], 'cuda:0')
inputs['Image'] = [image, img_weight]
if 'Text' in modality:
text = data.load_and_transform_text([text_path], 'cuda:0')
inputs['Text'] = [text, text_weight]
if 'Video' in modality:
video = data.load_and_transform_video_data([video_path], 'cuda:0')
inputs['Video'] = [video, video_weight]
if 'Audio' in modality:
audio = data.load_and_transform_audio_data([audio_path], 'cuda:0')
inputs['Audio'] = [audio, audio_weight]
if 'Point Cloud' in modality:
point = data.load_and_transform_point_cloud_data([point_path], 'cuda:0')
inputs['Point Cloud'] = [point, point_weight]
with torch.no_grad():
embeddings = self.imagebind_model(inputs)
return embeddings
def generate(self, modality, img_path, img_weight, text_path, text_weight, video_path, video_weight, audio_path, audio_weight, point_path, point_weight, max_new_tokens: int = 100, output_type: str = 'Text'):
embeddings = self.embed_multimodal_inputs(modality, img_path, img_weight, text_path, text_weight, video_path, video_weight, audio_path, audio_weight, point_path, point_weight)
if output_type == 'Text':
outputs = self.model.generate(embeddings, max_new_tokens=max_new_tokens)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
elif output_type == 'Image':
raise NotImplementedError('Image output is not yet implemented')
else:
raise ValueError('Output type not recognized')
class GalvatronUltra(GalvatronBaseLM):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.imagebind_model = imagebind_model.imagebind_huge(pretrained=True).eval().to("cuda:0")
def embed_multimodal_inputs(self, modality_data):
inputs = {}
load_and_transform = {
'Image': data.load_and_transform_vision_data,
'Text': data.load_and_transform_text,
'Video': data.load_and_transform_video_data,
'Audio': data.load_and_transform_audio_data,
'Point Cloud': data.load_and_transform_point_cloud_data,
}
for modality, data_path in modality_data.items():
if data_path is not None:
transformed_data = load_and_transform[modality]([data_path], 'cuda:0')
inputs[modality] = transformed_data
with torch.no_grad():
embeddings = self.imagebind_model(inputs)
return embeddings
def generate(self, modality_data, max_new_tokens: int = 100, output_type: str = 'Text'):
if not isinstance(modality_data, dict):
raise TypeError("modality_data must be of type dict")
for modality in modality_data:
if modality not in ['Image', 'Text', 'Video', 'Audio', 'Point Cloud']:
raise ValueError(f"Invalid modality: {modality}")
embeddings = self.embed_multimodal_inputs(modality_data)
if output_type == 'Text':
outputs = self.model.generate(embeddings, max_new_tokens=max_new_tokens)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
elif output_type == 'Image':
raise NotImplemented("Image output is not yet implemented")
else:
raise ValueError("Output type not recognized")
galvatronMega = GalvatronUltra(use_4bit_quantization=True)
modality_data = {
"Text": "Text data",
"Image": "/path/to/image.jpg",
"Audio": "/path/to/audio.mp3",
# "Video": "/path/to/video.mp4", # Uncomment if video data is available
# "Point Cloud": "/path/to/pointcloud.data", # Uncomment if point cloud data is available
}
response = galvatronMega.generate(modality_data)
print(response)
| Galvatron-master | Galvatron/model.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import math
import torch
import torch.nn as nn
import torchaudio
from PIL import Image
from pytorchvideo import transforms as pv_transforms
from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
from pytorchvideo.data.encoded_video import EncodedVideo
from torchvision import transforms
from torchvision.transforms._transforms_video import NormalizeVideo
from models.multimodal_preprocessors import SimpleTokenizer
DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
BPE_PATH = "bpe/bpe_simple_vocab_16e6.txt.gz"
def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
# Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
waveform -= waveform.mean()
fbank = torchaudio.compliance.kaldi.fbank(
waveform,
htk_compat=True,
sample_frequency=sample_rate,
use_energy=False,
window_type="hanning",
num_mel_bins=num_mel_bins,
dither=0.0,
frame_length=25,
frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
)
# Convert to [mel_bins, num_frames] shape
fbank = fbank.transpose(0, 1)
# Pad to target_length
n_frames = fbank.size(1)
p = target_length - n_frames
# if p is too large (say >20%), flash a warning
if abs(p) / n_frames > 0.2:
logging.warning(
"Large gap between audio n_frames(%d) and "
"target_length (%d). Is the audio_target_length "
"setting correct?",
n_frames,
target_length,
)
# cut and pad
if p > 0:
fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
elif p < 0:
fbank = fbank[:, 0:target_length]
# Convert to [1, mel_bins, num_frames] shape, essentially like a 1
# channel image
fbank = fbank.unsqueeze(0)
return fbank
def get_clip_timepoints(clip_sampler, duration):
# Read out all clips in this video
all_clips_timepoints = []
is_last_clip = False
end = 0.0
while not is_last_clip:
start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
all_clips_timepoints.append((start, end))
return all_clips_timepoints
def load_and_transform_vision_data(image_paths, device):
if image_paths is None:
return None
image_outputs = []
for image_path in image_paths:
data_transform = transforms.Compose(
[
transforms.Resize(
224, interpolation=transforms.InterpolationMode.BICUBIC
),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=(0.48145466, 0.4578275, 0.40821073),
std=(0.26862954, 0.26130258, 0.27577711),
),
]
)
with open(image_path, "rb") as fopen:
image = Image.open(fopen).convert("RGB")
image = data_transform(image).to(device)
image_outputs.append(image)
return torch.stack(image_outputs, dim=0)
def load_and_transform_text(text, device):
if text is None:
return None
tokenizer = SimpleTokenizer(bpe_path=BPE_PATH)
tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
tokens = torch.cat(tokens, dim=0)
return tokens
def load_and_transform_audio_data(
audio_paths,
device,
num_mel_bins=128,
target_length=204,
sample_rate=16000,
clip_duration=2,
clips_per_video=3,
mean=-4.268,
std=9.138,
):
if audio_paths is None:
return None
audio_outputs = []
clip_sampler = ConstantClipsPerVideoSampler(
clip_duration=clip_duration, clips_per_video=clips_per_video
)
for audio_path in audio_paths:
waveform, sr = torchaudio.load(audio_path)
if sample_rate != sr:
waveform = torchaudio.functional.resample(
waveform, orig_freq=sr, new_freq=sample_rate
)
all_clips_timepoints = get_clip_timepoints(
clip_sampler, waveform.size(1) / sample_rate
)
all_clips = []
for clip_timepoints in all_clips_timepoints:
waveform_clip = waveform[
:,
int(clip_timepoints[0] * sample_rate) : int(
clip_timepoints[1] * sample_rate
),
]
waveform_melspec = waveform2melspec(
waveform_clip, sample_rate, num_mel_bins, target_length
)
all_clips.append(waveform_melspec)
normalize = transforms.Normalize(mean=mean, std=std)
all_clips = [normalize(ac).to(device) for ac in all_clips]
all_clips = torch.stack(all_clips, dim=0)
audio_outputs.append(all_clips)
return torch.stack(audio_outputs, dim=0)
def crop_boxes(boxes, x_offset, y_offset):
"""
Perform crop on the bounding boxes given the offsets.
Args:
boxes (ndarray or None): bounding boxes to perform crop. The dimension
is `num boxes` x 4.
x_offset (int): cropping offset in the x axis.
y_offset (int): cropping offset in the y axis.
Returns:
cropped_boxes (ndarray or None): the cropped boxes with dimension of
`num boxes` x 4.
"""
cropped_boxes = boxes.copy()
cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
return cropped_boxes
def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
"""
Perform uniform spatial sampling on the images and corresponding boxes.
Args:
images (tensor): images to perform uniform crop. The dimension is
`num frames` x `channel` x `height` x `width`.
size (int): size of height and weight to crop the images.
spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
is larger than height. Or 0, 1, or 2 for top, center, and bottom
crop if height is larger than width.
boxes (ndarray or None): optional. Corresponding boxes to images.
Dimension is `num boxes` x 4.
scale_size (int): optinal. If not None, resize the images to scale_size before
performing any crop.
Returns:
cropped (tensor): images with dimension of
`num frames` x `channel` x `size` x `size`.
cropped_boxes (ndarray or None): the cropped boxes with dimension of
`num boxes` x 4.
"""
assert spatial_idx in [0, 1, 2]
ndim = len(images.shape)
if ndim == 3:
images = images.unsqueeze(0)
height = images.shape[2]
width = images.shape[3]
if scale_size is not None:
if width <= height:
width, height = scale_size, int(height / width * scale_size)
else:
width, height = int(width / height * scale_size), scale_size
images = torch.nn.functional.interpolate(
images,
size=(height, width),
mode="bilinear",
align_corners=False,
)
y_offset = int(math.ceil((height - size) / 2))
x_offset = int(math.ceil((width - size) / 2))
if height > width:
if spatial_idx == 0:
y_offset = 0
elif spatial_idx == 2:
y_offset = height - size
else:
if spatial_idx == 0:
x_offset = 0
elif spatial_idx == 2:
x_offset = width - size
cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
if ndim == 3:
cropped = cropped.squeeze(0)
return cropped, cropped_boxes
class SpatialCrop(nn.Module):
"""
Convert the video into 3 smaller clips spatially. Must be used after the
temporal crops to get spatial crops, and should be used with
-2 in the spatial crop at the slowfast augmentation stage (so full
frames are passed in here). Will return a larger list with the
3x spatial crops as well.
"""
def __init__(self, crop_size: int = 224, num_crops: int = 3):
super().__init__()
self.crop_size = crop_size
if num_crops == 3:
self.crops_to_ext = [0, 1, 2]
self.flipped_crops_to_ext = []
elif num_crops == 1:
self.crops_to_ext = [1]
self.flipped_crops_to_ext = []
else:
raise NotImplementedError("Nothing else supported yet")
def forward(self, videos):
"""
Args:
videos: A list of C, T, H, W videos.
Returns:
videos: A list with 3x the number of elements. Each video converted
to C, T, H', W' by spatial cropping.
"""
assert isinstance(videos, list), "Must be a list of videos after temporal crops"
assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
res = []
for video in videos:
for spatial_idx in self.crops_to_ext:
res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
if not self.flipped_crops_to_ext:
continue
flipped_video = transforms.functional.hflip(video)
for spatial_idx in self.flipped_crops_to_ext:
res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
return res
def load_and_transform_video_data(
video_paths,
device,
clip_duration=2,
clips_per_video=5,
sample_rate=16000,
):
if video_paths is None:
return None
video_outputs = []
video_transform = transforms.Compose(
[
pv_transforms.ShortSideScale(224),
NormalizeVideo(
mean=(0.48145466, 0.4578275, 0.40821073),
std=(0.26862954, 0.26130258, 0.27577711),
),
]
)
clip_sampler = ConstantClipsPerVideoSampler(
clip_duration=clip_duration, clips_per_video=clips_per_video
)
frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
for video_path in video_paths:
video = EncodedVideo.from_path(
video_path,
decoder="decord",
decode_audio=False,
**{"sample_rate": sample_rate},
)
all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
all_video = []
for clip_timepoints in all_clips_timepoints:
# Read the clip, get frames
clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
if clip is None:
raise ValueError("No clip found")
video_clip = frame_sampler(clip["video"])
video_clip = video_clip / 255.0 # since this is float, need 0-1
all_video.append(video_clip)
all_video = [video_transform(clip) for clip in all_video]
all_video = SpatialCrop(224, num_crops=3)(all_video)
all_video = torch.stack(all_video, dim=0)
video_outputs.append(all_video)
return torch.stack(video_outputs, dim=0).to(device)
| Galvatron-master | Galvatron/ImageBind/data.py |
Galvatron-master | Galvatron/ImageBind/models/__init__.py |
|
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from functools import partial
from types import SimpleNamespace
import torch
import torch.nn as nn
from models.helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize,
SelectElement, SelectEOSAndProject)
from models.multimodal_preprocessors import (AudioPreprocessor,
IMUPreprocessor, PadIm2Video,
PatchEmbedGeneric,
RGBDTPreprocessor,
SpatioTemporalPosEmbeddingHelper,
TextPreprocessor,
ThermalPreprocessor)
from models.transformer import MultiheadAttention, SimpleTransformer
ModalityType = SimpleNamespace(
VISION="vision",
TEXT="text",
AUDIO="audio",
THERMAL="thermal",
DEPTH="depth",
IMU="imu",
)
class ImageBindModel(nn.Module):
def __init__(
self,
video_frames=2,
kernel_size=(2, 14, 14),
audio_kernel_size=16,
audio_stride=10,
out_embed_dim=768,
vision_embed_dim=1024,
vision_num_blocks=24,
vision_num_heads=16,
audio_embed_dim=768,
audio_num_blocks=12,
audio_num_heads=12,
audio_num_mel_bins=128,
audio_target_len=204,
audio_drop_path=0.1,
text_embed_dim=768,
text_num_blocks=12,
text_num_heads=12,
depth_embed_dim=384,
depth_kernel_size=16,
depth_num_blocks=12,
depth_num_heads=8,
depth_drop_path=0.0,
thermal_embed_dim=768,
thermal_kernel_size=16,
thermal_num_blocks=12,
thermal_num_heads=12,
thermal_drop_path=0.0,
imu_embed_dim=512,
imu_kernel_size=8,
imu_num_blocks=6,
imu_num_heads=8,
imu_drop_path=0.7,
):
super().__init__()
self.modality_preprocessors = self._create_modality_preprocessors(
video_frames,
vision_embed_dim,
kernel_size,
text_embed_dim,
audio_embed_dim,
audio_kernel_size,
audio_stride,
audio_num_mel_bins,
audio_target_len,
depth_embed_dim,
depth_kernel_size,
thermal_embed_dim,
thermal_kernel_size,
imu_embed_dim,
)
self.modality_trunks = self._create_modality_trunks(
vision_embed_dim,
vision_num_blocks,
vision_num_heads,
text_embed_dim,
text_num_blocks,
text_num_heads,
audio_embed_dim,
audio_num_blocks,
audio_num_heads,
audio_drop_path,
depth_embed_dim,
depth_num_blocks,
depth_num_heads,
depth_drop_path,
thermal_embed_dim,
thermal_num_blocks,
thermal_num_heads,
thermal_drop_path,
imu_embed_dim,
imu_num_blocks,
imu_num_heads,
imu_drop_path,
)
self.modality_heads = self._create_modality_heads(
out_embed_dim,
vision_embed_dim,
text_embed_dim,
audio_embed_dim,
depth_embed_dim,
thermal_embed_dim,
imu_embed_dim,
)
self.modality_postprocessors = self._create_modality_postprocessors(
out_embed_dim
)
def _create_modality_preprocessors(
self,
video_frames=2,
vision_embed_dim=1024,
kernel_size=(2, 14, 14),
text_embed_dim=768,
audio_embed_dim=768,
audio_kernel_size=16,
audio_stride=10,
audio_num_mel_bins=128,
audio_target_len=204,
depth_embed_dim=768,
depth_kernel_size=16,
thermal_embed_dim=768,
thermal_kernel_size=16,
imu_embed_dim=512,
):
rgbt_stem = PatchEmbedGeneric(
proj_stem=[
PadIm2Video(pad_type="repeat", ntimes=2),
nn.Conv3d(
in_channels=3,
kernel_size=kernel_size,
out_channels=vision_embed_dim,
stride=kernel_size,
bias=False,
),
]
)
rgbt_preprocessor = RGBDTPreprocessor(
img_size=[3, video_frames, 224, 224],
num_cls_tokens=1,
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
rgbt_stem=rgbt_stem,
depth_stem=None,
)
text_preprocessor = TextPreprocessor(
context_length=77,
vocab_size=49408,
embed_dim=text_embed_dim,
causal_masking=True,
)
audio_stem = PatchEmbedGeneric(
proj_stem=[
nn.Conv2d(
in_channels=1,
kernel_size=audio_kernel_size,
stride=audio_stride,
out_channels=audio_embed_dim,
bias=False,
),
],
norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),
)
audio_preprocessor = AudioPreprocessor(
img_size=[1, audio_num_mel_bins, audio_target_len],
num_cls_tokens=1,
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
audio_stem=audio_stem,
)
depth_stem = PatchEmbedGeneric(
[
nn.Conv2d(
kernel_size=depth_kernel_size,
in_channels=1,
out_channels=depth_embed_dim,
stride=depth_kernel_size,
bias=False,
),
],
norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),
)
depth_preprocessor = RGBDTPreprocessor(
img_size=[1, 224, 224],
num_cls_tokens=1,
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
rgbt_stem=None,
depth_stem=depth_stem,
)
thermal_stem = PatchEmbedGeneric(
[
nn.Conv2d(
kernel_size=thermal_kernel_size,
in_channels=1,
out_channels=thermal_embed_dim,
stride=thermal_kernel_size,
bias=False,
),
],
norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),
)
thermal_preprocessor = ThermalPreprocessor(
img_size=[1, 224, 224],
num_cls_tokens=1,
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
thermal_stem=thermal_stem,
)
imu_stem = PatchEmbedGeneric(
[
nn.Linear(
in_features=48,
out_features=imu_embed_dim,
bias=False,
),
],
norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),
)
imu_preprocessor = IMUPreprocessor(
img_size=[6, 2000],
num_cls_tokens=1,
kernel_size=8,
embed_dim=imu_embed_dim,
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
imu_stem=imu_stem,
)
modality_preprocessors = {
ModalityType.VISION: rgbt_preprocessor,
ModalityType.TEXT: text_preprocessor,
ModalityType.AUDIO: audio_preprocessor,
ModalityType.DEPTH: depth_preprocessor,
ModalityType.THERMAL: thermal_preprocessor,
ModalityType.IMU: imu_preprocessor,
}
return nn.ModuleDict(modality_preprocessors)
def _create_modality_trunks(
self,
vision_embed_dim=1024,
vision_num_blocks=24,
vision_num_heads=16,
text_embed_dim=768,
text_num_blocks=12,
text_num_heads=12,
audio_embed_dim=768,
audio_num_blocks=12,
audio_num_heads=12,
audio_drop_path=0.0,
depth_embed_dim=768,
depth_num_blocks=12,
depth_num_heads=12,
depth_drop_path=0.0,
thermal_embed_dim=768,
thermal_num_blocks=12,
thermal_num_heads=12,
thermal_drop_path=0.0,
imu_embed_dim=512,
imu_num_blocks=6,
imu_num_heads=8,
imu_drop_path=0.7,
):
def instantiate_trunk(
embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path
):
return SimpleTransformer(
embed_dim=embed_dim,
num_blocks=num_blocks,
ffn_dropout_rate=0.0,
drop_path_rate=drop_path,
attn_target=partial(
MultiheadAttention,
embed_dim=embed_dim,
num_heads=num_heads,
bias=True,
add_bias_kv=add_bias_kv,
),
pre_transformer_layer=nn.Sequential(
nn.LayerNorm(embed_dim, eps=1e-6)
if pre_transformer_ln
else nn.Identity(),
EinOpsRearrange("b l d -> l b d"),
),
post_transformer_layer=EinOpsRearrange("l b d -> b l d"),
)
modality_trunks = {}
modality_trunks[ModalityType.VISION] = instantiate_trunk(
vision_embed_dim,
vision_num_blocks,
vision_num_heads,
pre_transformer_ln=True,
add_bias_kv=False,
drop_path=0.0,
)
modality_trunks[ModalityType.TEXT] = instantiate_trunk(
text_embed_dim,
text_num_blocks,
text_num_heads,
pre_transformer_ln=False,
add_bias_kv=False,
drop_path=0.0,
)
modality_trunks[ModalityType.AUDIO] = instantiate_trunk(
audio_embed_dim,
audio_num_blocks,
audio_num_heads,
pre_transformer_ln=False,
add_bias_kv=True,
drop_path=audio_drop_path,
)
modality_trunks[ModalityType.DEPTH] = instantiate_trunk(
depth_embed_dim,
depth_num_blocks,
depth_num_heads,
pre_transformer_ln=False,
add_bias_kv=True,
drop_path=depth_drop_path,
)
modality_trunks[ModalityType.THERMAL] = instantiate_trunk(
thermal_embed_dim,
thermal_num_blocks,
thermal_num_heads,
pre_transformer_ln=False,
add_bias_kv=True,
drop_path=thermal_drop_path,
)
modality_trunks[ModalityType.IMU] = instantiate_trunk(
imu_embed_dim,
imu_num_blocks,
imu_num_heads,
pre_transformer_ln=False,
add_bias_kv=True,
drop_path=imu_drop_path,
)
return nn.ModuleDict(modality_trunks)
def _create_modality_heads(
self,
out_embed_dim,
vision_embed_dim,
text_embed_dim,
audio_embed_dim,
depth_embed_dim,
thermal_embed_dim,
imu_embed_dim,
):
modality_heads = {}
modality_heads[ModalityType.VISION] = nn.Sequential(
nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),
SelectElement(index=0),
nn.Linear(vision_embed_dim, out_embed_dim, bias=False),
)
modality_heads[ModalityType.TEXT] = SelectEOSAndProject(
proj=nn.Sequential(
nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),
nn.Linear(text_embed_dim, out_embed_dim, bias=False),
)
)
modality_heads[ModalityType.AUDIO] = nn.Sequential(
nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),
SelectElement(index=0),
nn.Linear(audio_embed_dim, out_embed_dim, bias=False),
)
modality_heads[ModalityType.DEPTH] = nn.Sequential(
nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),
SelectElement(index=0),
nn.Linear(depth_embed_dim, out_embed_dim, bias=False),
)
modality_heads[ModalityType.THERMAL] = nn.Sequential(
nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),
SelectElement(index=0),
nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),
)
modality_heads[ModalityType.IMU] = nn.Sequential(
nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),
SelectElement(index=0),
nn.Dropout(p=0.5),
nn.Linear(imu_embed_dim, out_embed_dim, bias=False),
)
return nn.ModuleDict(modality_heads)
def _create_modality_postprocessors(self, out_embed_dim):
modality_postprocessors = {}
modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)
modality_postprocessors[ModalityType.TEXT] = nn.Sequential(
Normalize(dim=-1), LearnableLogitScaling(learnable=True)
)
modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(
Normalize(dim=-1),
LearnableLogitScaling(logit_scale_init=20.0, learnable=False),
)
modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(
Normalize(dim=-1),
LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
)
modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(
Normalize(dim=-1),
LearnableLogitScaling(logit_scale_init=10.0, learnable=False),
)
modality_postprocessors[ModalityType.IMU] = nn.Sequential(
Normalize(dim=-1),
LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
)
return nn.ModuleDict(modality_postprocessors)
def forward(self, inputs):
outputs = {}
for modality_key, modality_value in inputs.items():
reduce_list = (
modality_value.ndim >= 5
) # Audio and Video inputs consist of multiple clips
if reduce_list:
B, S = modality_value.shape[:2]
modality_value = modality_value.reshape(
B * S, *modality_value.shape[2:]
)
if modality_value is not None:
modality_value = self.modality_preprocessors[modality_key](
**{modality_key: modality_value}
)
trunk_inputs = modality_value["trunk"]
head_inputs = modality_value["head"]
modality_value = self.modality_trunks[modality_key](**trunk_inputs)
modality_value = self.modality_heads[modality_key](
modality_value, **head_inputs
)
modality_value = self.modality_postprocessors[modality_key](
modality_value
)
if reduce_list:
modality_value = modality_value.reshape(B, S, -1)
modality_value = modality_value.mean(dim=1)
outputs[modality_key] = modality_value
return outputs
def imagebind_huge(pretrained=False):
model = ImageBindModel(
vision_embed_dim=1280,
vision_num_blocks=32,
vision_num_heads=16,
text_embed_dim=1024,
text_num_blocks=24,
text_num_heads=16,
out_embed_dim=1024,
audio_drop_path=0.1,
imu_drop_path=0.7,
)
if pretrained:
if not os.path.exists(".checkpoints/imagebind_huge.pth"):
print(
"Downloading imagebind weights to .checkpoints/imagebind_huge.pth ..."
)
os.makedirs(".checkpoints", exist_ok=True)
torch.hub.download_url_to_file(
"https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth",
".checkpoints/imagebind_huge.pth",
progress=True,
)
model.load_state_dict(torch.load(".checkpoints/imagebind_huge.pth"))
return model
| Galvatron-master | Galvatron/ImageBind/models/imagebind_model.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Code modified from
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;
# https://github.com/facebookresearch/deit/blob/main/models.py
# and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py
from functools import partial
from typing import Callable, List, Optional
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, trunc_normal_
class Attention(nn.Module):
def __init__(
self,
dim,
num_heads=8,
qkv_bias=False,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version,
# can set manually to be compat with prev weights
self.scale = qk_scale or head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = (
self.qkv(x)
.reshape(B, N, 3, self.num_heads, C // self.num_heads)
.permute(2, 0, 3, 1, 4)
)
q, k, v = (
qkv[0],
qkv[1],
qkv[2],
) # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class MultiheadAttention(nn.MultiheadAttention):
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
class ViTAttention(Attention):
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
assert attn_mask is None
return super().forward(x)
class BlockWithMasking(nn.Module):
def __init__(
self,
dim: int,
attn_target: Callable,
mlp_ratio: int = 4,
act_layer: Callable = nn.GELU,
norm_layer: Callable = nn.LayerNorm,
ffn_dropout_rate: float = 0.0,
drop_path: float = 0.0,
layer_scale_type: Optional[str] = None,
layer_scale_init_value: float = 1e-4,
):
super().__init__()
assert not isinstance(
attn_target, nn.Module
), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!"
self.attn = attn_target()
if drop_path > 0.0:
self.drop_path = DropPath(drop_path)
else:
self.drop_path = nn.Identity()
self.norm_1 = norm_layer(dim)
mlp_hidden_dim = int(mlp_ratio * dim)
self.mlp = Mlp(
in_features=dim,
hidden_features=mlp_hidden_dim,
act_layer=act_layer,
drop=ffn_dropout_rate,
)
self.norm_2 = norm_layer(dim)
self.layer_scale_type = layer_scale_type
if self.layer_scale_type is not None:
assert self.layer_scale_type in [
"per_channel",
"scalar",
], f"Found Layer scale type {self.layer_scale_type}"
if self.layer_scale_type == "per_channel":
# one gamma value per channel
gamma_shape = [1, 1, dim]
elif self.layer_scale_type == "scalar":
# single gamma value for all channels
gamma_shape = [1, 1, 1]
# two gammas: for each part of the fwd in the encoder
self.layer_scale_gamma1 = nn.Parameter(
torch.ones(size=gamma_shape) * layer_scale_init_value,
requires_grad=True,
)
self.layer_scale_gamma2 = nn.Parameter(
torch.ones(size=gamma_shape) * layer_scale_init_value,
requires_grad=True,
)
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
if self.layer_scale_type is None:
x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
x = x + self.drop_path(self.mlp(self.norm_2(x)))
else:
x = (
x
+ self.drop_path(self.attn(self.norm_1(x), attn_mask))
* self.layer_scale_gamma1
)
x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2
return x
_LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)
class SimpleTransformer(nn.Module):
def __init__(
self,
attn_target: Callable,
embed_dim: int,
num_blocks: int,
block: Callable = BlockWithMasking,
pre_transformer_layer: Optional[Callable] = None,
post_transformer_layer: Optional[Callable] = None,
drop_path_rate: float = 0.0,
drop_path_type: str = "progressive",
norm_layer: Callable = _LAYER_NORM,
mlp_ratio: int = 4,
ffn_dropout_rate: float = 0.0,
layer_scale_type: Optional[str] = None, # from cait; possible values are None, "per_channel", "scalar"
layer_scale_init_value: float = 1e-4, # from cait; float
weight_init_style: str = "jax", # possible values jax or pytorch
):
"""
Simple Transformer with the following features
1. Supports masked attention
2. Supports DropPath
3. Supports LayerScale
4. Supports Dropout in Attention and FFN
5. Makes few assumptions about the input except that it is a Tensor
"""
super().__init__()
self.pre_transformer_layer = pre_transformer_layer
if drop_path_type == "progressive":
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]
elif drop_path_type == "uniform":
dpr = [drop_path_rate for i in range(num_blocks)]
else:
raise ValueError(f"Unknown drop_path_type: {drop_path_type}")
self.blocks = nn.Sequential(
*[
block(
dim=embed_dim,
attn_target=attn_target,
mlp_ratio=mlp_ratio,
ffn_dropout_rate=ffn_dropout_rate,
drop_path=dpr[i],
norm_layer=norm_layer,
layer_scale_type=layer_scale_type,
layer_scale_init_value=layer_scale_init_value,
)
for i in range(num_blocks)
]
)
self.post_transformer_layer = post_transformer_layer
self.weight_init_style = weight_init_style
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
if self.weight_init_style == "jax":
# Based on MAE and official Jax ViT implementation
torch.nn.init.xavier_uniform_(m.weight)
elif self.weight_init_style == "pytorch":
# PyTorch ViT uses trunc_normal_
trunc_normal_(m.weight, std=0.02)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, (nn.LayerNorm)):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def forward(
self,
tokens: torch.Tensor,
attn_mask: torch.Tensor = None,
use_checkpoint: bool = False,
checkpoint_every_n: int = 1,
checkpoint_blk_ids: Optional[List[int]] = None,
):
"""
Inputs
- tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)
- attn: mask of shape L x L
Output
- x: data of shape N x L x D (or L x N x D depending on the attention implementation)
"""
if self.pre_transformer_layer:
tokens = self.pre_transformer_layer(tokens)
if use_checkpoint and checkpoint_blk_ids is None:
checkpoint_blk_ids = [
blk_id
for blk_id in range(len(self.blocks))
if blk_id % checkpoint_every_n == 0
]
if checkpoint_blk_ids:
checkpoint_blk_ids = set(checkpoint_blk_ids)
for blk_id, blk in enumerate(self.blocks):
if use_checkpoint and blk_id in checkpoint_blk_ids:
tokens = checkpoint.checkpoint(
blk, tokens, attn_mask, use_reentrant=False
)
else:
tokens = blk(tokens, attn_mask=attn_mask)
if self.post_transformer_layer:
tokens = self.post_transformer_layer(tokens)
return tokens
| Galvatron-master | Galvatron/ImageBind/models/transformer.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import gzip
import html
import io
import math
from functools import lru_cache
from typing import Callable, List, Optional, Tuple
import ftfy
import numpy as np
import regex as re
import torch
import torch.nn as nn
from iopath.common.file_io import g_pathmgr
from timm.models.layers import trunc_normal_
from models.helpers import VerboseNNModule, cast_if_src_dtype
def get_sinusoid_encoding_table(n_position, d_hid):
"""Sinusoid position encoding table"""
# TODO: make it with torch instead of numpy
def get_position_angle_vec(position):
return [
position / np.power(10000, 2 * (hid_j // 2) / d_hid)
for hid_j in range(d_hid)
]
sinusoid_table = np.array(
[get_position_angle_vec(pos_i) for pos_i in range(n_position)]
)
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
return torch.FloatTensor(sinusoid_table).unsqueeze(0)
def interpolate_pos_encoding_2d(target_spatial_size, pos_embed):
N = pos_embed.shape[1]
if N == target_spatial_size:
return pos_embed
dim = pos_embed.shape[-1]
# nn.functional.interpolate doesn't work with bfloat16 so we cast to float32
pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)
pos_embed = nn.functional.interpolate(
pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(
0, 3, 1, 2
),
scale_factor=math.sqrt(target_spatial_size / N),
mode="bicubic",
)
if updated:
pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)
pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
return pos_embed
def interpolate_pos_encoding(
npatch_per_img,
pos_embed,
patches_layout,
input_shape=None,
first_patch_idx=1,
):
assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none"
N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists
if npatch_per_img == N:
return pos_embed
assert (
patches_layout[-1] == patches_layout[-2]
), "Interpolation of pos embed not supported for non-square layouts"
class_emb = pos_embed[:, :first_patch_idx]
pos_embed = pos_embed[:, first_patch_idx:]
if input_shape is None or patches_layout[0] == 1:
# simple 2D pos embedding, no temporal component
pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)
elif patches_layout[0] > 1:
# pos embed has a temporal component
assert len(input_shape) == 4, "temporal interpolation not supported"
# we only support 2D interpolation in this case
num_frames = patches_layout[0]
num_spatial_tokens = patches_layout[1] * patches_layout[2]
pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)
# interpolate embedding for zeroth frame
pos_embed = interpolate_pos_encoding_2d(
npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)
)
else:
raise ValueError("This type of interpolation isn't implemented")
return torch.cat((class_emb, pos_embed), dim=1)
def _get_pos_embedding(
npatch_per_img,
pos_embed,
patches_layout,
input_shape,
first_patch_idx=1,
):
pos_embed = interpolate_pos_encoding(
npatch_per_img,
pos_embed,
patches_layout,
input_shape=input_shape,
first_patch_idx=first_patch_idx,
)
return pos_embed
class PatchEmbedGeneric(nn.Module):
"""
PatchEmbed from Hydra
"""
def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):
super().__init__()
if len(proj_stem) > 1:
self.proj = nn.Sequential(*proj_stem)
else:
# Special case to be able to load pre-trained models that were
# trained with a standard stem
self.proj = proj_stem[0]
self.norm_layer = norm_layer
def get_patch_layout(self, img_size):
with torch.no_grad():
dummy_img = torch.zeros(
[
1,
]
+ img_size
)
dummy_out = self.proj(dummy_img)
embed_dim = dummy_out.shape[1]
patches_layout = tuple(dummy_out.shape[2:])
num_patches = np.prod(patches_layout)
return patches_layout, num_patches, embed_dim
def forward(self, x):
x = self.proj(x)
# B C (T) H W -> B (T)HW C
x = x.flatten(2).transpose(1, 2)
if self.norm_layer is not None:
x = self.norm_layer(x)
return x
class SpatioTemporalPosEmbeddingHelper(VerboseNNModule):
def __init__(
self,
patches_layout: List,
num_patches: int,
num_cls_tokens: int,
embed_dim: int,
learnable: bool,
) -> None:
super().__init__()
self.num_cls_tokens = num_cls_tokens
self.patches_layout = patches_layout
self.num_patches = num_patches
self.num_tokens = num_cls_tokens + num_patches
self.learnable = learnable
if self.learnable:
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
trunc_normal_(self.pos_embed, std=0.02)
else:
self.register_buffer(
"pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim)
)
def get_pos_embedding(self, vision_input, all_vision_tokens):
input_shape = vision_input.shape
pos_embed = _get_pos_embedding(
all_vision_tokens.size(1) - self.num_cls_tokens,
pos_embed=self.pos_embed,
patches_layout=self.patches_layout,
input_shape=input_shape,
first_patch_idx=self.num_cls_tokens,
)
return pos_embed
class RGBDTPreprocessor(VerboseNNModule):
def __init__(
self,
rgbt_stem: PatchEmbedGeneric,
depth_stem: Optional[PatchEmbedGeneric],
img_size: Tuple = (3, 224, 224),
num_cls_tokens: int = 1,
pos_embed_fn: Optional[Callable] = None,
use_type_embed: bool = False,
init_param_style: str = "openclip",
) -> None:
super().__init__()
stem = rgbt_stem if rgbt_stem is not None else depth_stem
(
self.patches_layout,
self.num_patches,
self.embed_dim,
) = stem.get_patch_layout(img_size)
self.rgbt_stem = rgbt_stem
self.depth_stem = depth_stem
self.use_pos_embed = pos_embed_fn is not None
self.use_type_embed = use_type_embed
self.num_cls_tokens = num_cls_tokens
if self.use_pos_embed:
self.pos_embedding_helper = pos_embed_fn(
patches_layout=self.patches_layout,
num_cls_tokens=num_cls_tokens,
num_patches=self.num_patches,
embed_dim=self.embed_dim,
)
if self.num_cls_tokens > 0:
self.cls_token = nn.Parameter(
torch.zeros(1, self.num_cls_tokens, self.embed_dim)
)
if self.use_type_embed:
self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.init_parameters(init_param_style)
@torch.no_grad()
def init_parameters(self, init_param_style):
if init_param_style == "openclip":
# OpenCLIP style initialization
scale = self.embed_dim**-0.5
if self.use_pos_embed:
nn.init.normal_(self.pos_embedding_helper.pos_embed)
self.pos_embedding_helper.pos_embed *= scale
if self.num_cls_tokens > 0:
nn.init.normal_(self.cls_token)
self.cls_token *= scale
elif init_param_style == "vit":
self.cls_token.data.fill_(0)
else:
raise ValueError(f"Unknown init {init_param_style}")
if self.use_type_embed:
nn.init.normal_(self.type_embed)
def tokenize_input_and_cls_pos(self, input, stem, mask):
# tokens is of shape B x L x D
tokens = stem(input)
assert tokens.ndim == 3
assert tokens.shape[2] == self.embed_dim
B = tokens.shape[0]
if self.num_cls_tokens > 0:
class_tokens = self.cls_token.expand(
B, -1, -1
) # stole class_tokens impl from Phil Wang, thanks
tokens = torch.cat((class_tokens, tokens), dim=1)
if self.use_pos_embed:
pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)
tokens = tokens + pos_embed
if self.use_type_embed:
tokens = tokens + self.type_embed.expand(B, -1, -1)
return tokens
def forward(self, vision=None, depth=None, patch_mask=None):
if patch_mask is not None:
raise NotImplementedError()
if vision is not None:
vision_tokens = self.tokenize_input_and_cls_pos(
vision, self.rgbt_stem, patch_mask
)
if depth is not None:
depth_tokens = self.tokenize_input_and_cls_pos(
depth, self.depth_stem, patch_mask
)
# aggregate tokens
if vision is not None and depth is not None:
final_tokens = vision_tokens + depth_tokens
else:
final_tokens = vision_tokens if vision is not None else depth_tokens
return_dict = {
"trunk": {
"tokens": final_tokens,
},
"head": {},
}
return return_dict
class AudioPreprocessor(RGBDTPreprocessor):
def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:
super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)
def forward(self, audio=None):
return super().forward(vision=audio)
class ThermalPreprocessor(RGBDTPreprocessor):
def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:
super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)
def forward(self, thermal=None):
return super().forward(vision=thermal)
def build_causal_attention_mask(context_length):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(context_length, context_length, requires_grad=False)
mask.fill_(float("-inf"))
mask.triu_(1) # zero out the lower diagonal
return mask
class TextPreprocessor(VerboseNNModule):
def __init__(
self,
vocab_size: int,
context_length: int,
embed_dim: int,
causal_masking: bool,
supply_seq_len_to_head: bool = True,
num_cls_tokens: int = 0,
init_param_style: str = "openclip",
) -> None:
super().__init__()
self.vocab_size = vocab_size
self.context_length = context_length
self.token_embedding = nn.Embedding(vocab_size, embed_dim)
self.pos_embed = nn.Parameter(
torch.empty(1, self.context_length + num_cls_tokens, embed_dim)
)
self.causal_masking = causal_masking
if self.causal_masking:
mask = build_causal_attention_mask(self.context_length)
# register the mask as a buffer so it can be moved to the right device
self.register_buffer("mask", mask)
self.supply_seq_len_to_head = supply_seq_len_to_head
self.num_cls_tokens = num_cls_tokens
self.embed_dim = embed_dim
if num_cls_tokens > 0:
assert self.causal_masking is False, "Masking + CLS token isn't implemented"
self.cls_token = nn.Parameter(
torch.zeros(1, self.num_cls_tokens, embed_dim)
)
self.init_parameters(init_param_style)
@torch.no_grad()
def init_parameters(self, init_param_style="openclip"):
# OpenCLIP style initialization
nn.init.normal_(self.token_embedding.weight, std=0.02)
nn.init.normal_(self.pos_embed, std=0.01)
if init_param_style == "openclip":
# OpenCLIP style initialization
scale = self.embed_dim**-0.5
if self.num_cls_tokens > 0:
nn.init.normal_(self.cls_token)
self.cls_token *= scale
elif init_param_style == "vit":
self.cls_token.data.fill_(0)
else:
raise ValueError(f"Unknown init {init_param_style}")
def forward(self, text):
# text tokens are of shape B x L x D
text_tokens = self.token_embedding(text)
# concat CLS tokens if any
if self.num_cls_tokens > 0:
B = text_tokens.shape[0]
class_tokens = self.cls_token.expand(
B, -1, -1
) # stole class_tokens impl from Phil Wang, thanks
text_tokens = torch.cat((class_tokens, text_tokens), dim=1)
text_tokens = text_tokens + self.pos_embed
return_dict = {
"trunk": {
"tokens": text_tokens,
},
"head": {},
}
# Compute sequence length after adding CLS tokens
if self.supply_seq_len_to_head:
text_lengths = text.argmax(dim=-1)
return_dict["head"] = {
"seq_len": text_lengths,
}
if self.causal_masking:
return_dict["trunk"].update({"attn_mask": self.mask})
return return_dict
class Im2Video(nn.Module):
"""Convert an image into a trivial video."""
def __init__(self, time_dim=2):
super().__init__()
self.time_dim = time_dim
def forward(self, x):
if x.ndim == 4:
# B, C, H, W -> B, C, T, H, W
return x.unsqueeze(self.time_dim)
elif x.ndim == 5:
return x
else:
raise ValueError(f"Dimension incorrect {x.shape}")
class PadIm2Video(Im2Video):
def __init__(self, ntimes, pad_type, time_dim=2):
super().__init__(time_dim=time_dim)
assert ntimes > 0
assert pad_type in ["zero", "repeat"]
self.ntimes = ntimes
self.pad_type = pad_type
def forward(self, x):
x = super().forward(x)
if x.shape[self.time_dim] == 1:
if self.pad_type == "repeat":
new_shape = [1] * len(x.shape)
new_shape[self.time_dim] = self.ntimes
x = x.repeat(new_shape)
elif self.pad_type == "zero":
padarg = [0, 0] * len(x.shape)
padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]
x = nn.functional.pad(x, padarg)
return x
# Modified from github.com/openai/CLIP
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
This is a signficant percentage of your normal, say, 32K bpe vocab.
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
And avoids mapping to whitespace/control characters the bpe code barfs on.
"""
bs = (
list(range(ord("!"), ord("~") + 1))
+ list(range(ord("¡"), ord("¬") + 1))
+ list(range(ord("®"), ord("ÿ") + 1))
)
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
bs.append(b)
cs.append(2**8 + n)
n += 1
cs = [chr(n) for n in cs]
return dict(zip(bs, cs))
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
def whitespace_clean(text):
text = re.sub(r"\s+", " ", text)
text = text.strip()
return text
class SimpleTokenizer(object):
def __init__(self, bpe_path: str, context_length=77):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
with g_pathmgr.open(bpe_path, "rb") as fh:
bpe_bytes = io.BytesIO(fh.read())
merges: List[str] = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
merges = merges[1 : 49152 - 256 - 2 + 1]
merges: List[Tuple[str, ...]] = [tuple(merge.split()) for merge in merges]
vocab = list(bytes_to_unicode().values())
vocab = vocab + [v + "</w>" for v in vocab]
for merge in merges:
vocab.append("".join(merge))
vocab.extend(["<|startoftext|>", "<|endoftext|>"])
self.encoder = dict(zip(vocab, range(len(vocab))))
self.decoder = {v: k for k, v in self.encoder.items()}
self.bpe_ranks = dict(zip(merges, range(len(merges))))
self.cache = {
"<|startoftext|>": "<|startoftext|>",
"<|endoftext|>": "<|endoftext|>",
}
self.pat = re.compile(
r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
re.IGNORECASE,
)
self.context_length = context_length
def bpe(self, token):
if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + (token[-1] + "</w>",)
pairs = get_pairs(word)
if not pairs:
return token + "</w>"
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
if bigram not in self.bpe_ranks:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
new_word.extend(word[i:j])
i = j
except:
new_word.extend(word[i:])
break
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
word = " ".join(word)
self.cache[token] = word
return word
def encode(self, text):
bpe_tokens = []
text = whitespace_clean(basic_clean(text)).lower()
for token in re.findall(self.pat, text):
token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
bpe_tokens.extend(
self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
)
return bpe_tokens
def decode(self, tokens):
text = "".join([self.decoder[token] for token in tokens])
text = (
bytearray([self.byte_decoder[c] for c in text])
.decode("utf-8", errors="replace")
.replace("</w>", " ")
)
return text
def __call__(self, texts, context_length=None):
if not context_length:
context_length = self.context_length
if isinstance(texts, str):
texts = [texts]
sot_token = self.encoder["<|startoftext|>"]
eot_token = self.encoder["<|endoftext|>"]
all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts]
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
for i, tokens in enumerate(all_tokens):
tokens = tokens[:context_length]
result[i, : len(tokens)] = torch.tensor(tokens)
if len(result) == 1:
return result[0]
return result
class IMUPreprocessor(VerboseNNModule):
def __init__(
self,
kernel_size: int,
imu_stem: PatchEmbedGeneric,
embed_dim: int,
img_size: Tuple = (6, 2000),
num_cls_tokens: int = 1,
pos_embed_fn: Optional[Callable] = None,
init_param_style: str = "openclip",
) -> None:
super().__init__()
self.imu_stem = imu_stem
self.embed_dim = embed_dim
self.use_pos_embed = pos_embed_fn is not None
self.num_cls_tokens = num_cls_tokens
self.kernel_size = kernel_size
self.pos_embed = nn.Parameter(
torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)
)
if self.num_cls_tokens > 0:
self.cls_token = nn.Parameter(
torch.zeros(1, self.num_cls_tokens, self.embed_dim)
)
self.init_parameters(init_param_style)
@torch.no_grad()
def init_parameters(self, init_param_style):
nn.init.normal_(self.pos_embed, std=0.01)
if init_param_style == "openclip":
# OpenCLIP style initialization
scale = self.embed_dim**-0.5
if self.num_cls_tokens > 0:
nn.init.normal_(self.cls_token)
self.cls_token *= scale
elif init_param_style == "vit":
self.cls_token.data.fill_(0)
else:
raise ValueError(f"Unknown init {init_param_style}")
def tokenize_input_and_cls_pos(self, input, stem):
# tokens is of shape B x L x D
tokens = stem.norm_layer(stem.proj(input))
assert tokens.ndim == 3
assert tokens.shape[2] == self.embed_dim
B = tokens.shape[0]
if self.num_cls_tokens > 0:
class_tokens = self.cls_token.expand(
B, -1, -1
) # stole class_tokens impl from Phil Wang, thanks
tokens = torch.cat((class_tokens, tokens), dim=1)
if self.use_pos_embed:
tokens = tokens + self.pos_embed
return tokens
def forward(self, imu):
# Patchify
imu = imu.unfold(
-1,
self.kernel_size,
self.kernel_size,
).permute(0, 2, 1, 3)
imu = imu.reshape(imu.size(0), imu.size(1), -1)
imu_tokens = self.tokenize_input_and_cls_pos(
imu,
self.imu_stem,
)
return_dict = {
"trunk": {
"tokens": imu_tokens,
},
"head": {},
}
return return_dict
| Galvatron-master | Galvatron/ImageBind/models/multimodal_preprocessors.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import einops
import numpy as np
import torch
import torch.nn as nn
class Normalize(nn.Module):
def __init__(self, dim: int) -> None:
super().__init__()
self.dim = dim
def forward(self, x):
return torch.nn.functional.normalize(x, dim=self.dim, p=2)
class LearnableLogitScaling(nn.Module):
def __init__(
self,
logit_scale_init: float = 1 / 0.07,
learnable: bool = True,
max_logit_scale: float = 100,
) -> None:
super().__init__()
self.max_logit_scale = max_logit_scale
self.logit_scale_init = logit_scale_init
self.learnable = learnable
log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)
if learnable:
self.log_logit_scale = nn.Parameter(log_logit_scale)
else:
self.register_buffer("log_logit_scale", log_logit_scale)
def forward(self, x):
return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x
def extra_repr(self):
st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}," \
f" max_logit_scale={self.max_logit_scale}"
return st
class EinOpsRearrange(nn.Module):
def __init__(self, rearrange_expr: str, **kwargs) -> None:
super().__init__()
self.rearrange_expr = rearrange_expr
self.kwargs = kwargs
def forward(self, x):
assert isinstance(x, torch.Tensor)
return einops.rearrange(x, self.rearrange_expr, **self.kwargs)
class VerboseNNModule(nn.Module):
"""
Wrapper around nn.Module that prints registered buffers and parameter names.
"""
@staticmethod
def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:
st = (
"("
+ name
+ "): "
+ "tensor("
+ str(tuple(tensor[1].shape))
+ ", requires_grad="
+ str(tensor[1].requires_grad)
+ ")\n"
)
return st
def extra_repr(self) -> str:
named_modules = set()
for p in self.named_modules():
named_modules.update([p[0]])
named_modules = list(named_modules)
string_repr = ""
for p in self.named_parameters():
name = p[0].split(".")[0]
if name not in named_modules:
string_repr += self.get_readable_tensor_repr(name, p)
for p in self.named_buffers():
name = p[0].split(".")[0]
string_repr += self.get_readable_tensor_repr(name, p)
return string_repr
def cast_if_src_dtype(
tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype
):
updated = False
if tensor.dtype == src_dtype:
tensor = tensor.to(dtype=tgt_dtype)
updated = True
return tensor, updated
class QuickGELU(nn.Module):
# From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class SelectElement(nn.Module):
def __init__(self, index) -> None:
super().__init__()
self.index = index
def forward(self, x):
assert x.ndim >= 3
return x[:, self.index, ...]
class SelectEOSAndProject(nn.Module):
"""
Text Pooling used in OpenCLIP
"""
def __init__(self, proj: nn.Module) -> None:
super().__init__()
self.proj = proj
def forward(self, x, seq_len):
assert x.ndim == 3
# x is of shape B x L x D
# take features from the eot embedding (eot_token is the highest number in each sequence)
x = x[torch.arange(x.shape[0]), seq_len]
x = self.proj(x)
return x
| Galvatron-master | Galvatron/ImageBind/models/helpers.py |
from profit.main import ProfitPilot
# Define variables for ProfitPilot
AI_NAME = "Athena"
AI_ROLE = "Sales Representative"
EXTERNAL_TOOLS = None
COMPANY_NAME = "ABC Company"
COMPANY_VALUES = "Quality, Innovation, Customer Satisfaction"
CONVERSATION_TYPE = "Cold Email"
CONVERSATION_PURPOSE = "discuss our new product"
COMPANY_BUSINESS = "APAC AI"
SALESPERSON_NAME = "John Doe"
HUMAN_IN_THE_LOOP = False
PROSPECT_NAME = "Jane Smith" # Add the prospect's name here
# Create an instance of the ProfitPilot class
pilot = ProfitPilot(
ai_name=AI_NAME,
ai_role=AI_ROLE,
external_tools=EXTERNAL_TOOLS,
company_name=COMPANY_NAME,
company_values=COMPANY_VALUES,
conversation_type=CONVERSATION_TYPE,
conversation_purpose=CONVERSATION_PURPOSE,
company_business=COMPANY_BUSINESS,
salesperson_name=SALESPERSON_NAME,
human_in_the_loop=HUMAN_IN_THE_LOOP,
llama=True,
openai_api_key="key"
)
# Define the task you want the agent to perform
# Adjusted for email format
task = f"""
Subject: Introducing {COMPANY_NAME}'s Newest Product—A Perfect Fit for {PROSPECT_NAME}
Hi {PROSPECT_NAME},
I hope this email finds you well. My name is {SALESPERSON_NAME}, and I'm with {COMPANY_NAME}. We specialize in {COMPANY_BUSINESS}, and I'm excited to share some news that aligns closely with your values—{COMPANY_VALUES}.
I'd love the opportunity to discuss our latest product with you. Would you be open to exploring how it could benefit your team?
Looking forward to your response!
Best,
{SALESPERSON_NAME}
"""
# Run the task using the ProfitPilot instance
pilot.run(task) | ProfitPilot-main | example.py |
import streamlit as st
from profit.main import ProfitPilot
from clarifai_utils.modules.css import ClarifaiStreamlitCSS
st.set_page_config(layout="wide")
ClarifaiStreamlitCSS.insert_default_css(st)
st.markdown("Please select a specific page from the sidebar to the left")
# Define variables for ProfitPilot
AI_NAME = "Athena"
AI_ROLE = "Sales Representative"
EXTERNAL_TOOLS = None
COMPANY_NAME = "ABC Company"
COMPANY_VALUES = "Quality, Innovation, Customer Satisfaction"
CONVERSATION_TYPE = "Cold Email"
CONVERSATION_PURPOSE = "discuss our new product"
COMPANY_BUSINESS = "APAC AI"
SALESPERSON_NAME = "John Doe"
HUMAN_IN_THE_LOOP = False
PROSPECT_NAME = "Jane Smith" # Add the prospect's name here
# Create an instance of the ProfitPilot class
pilot = ProfitPilot(
ai_name=AI_NAME,
ai_role=AI_ROLE,
external_tools=EXTERNAL_TOOLS,
company_name=COMPANY_NAME,
company_values=COMPANY_VALUES,
conversation_type=CONVERSATION_TYPE,
conversation_purpose=CONVERSATION_PURPOSE,
company_business=COMPANY_BUSINESS,
salesperson_name=SALESPERSON_NAME,
human_in_the_loop=HUMAN_IN_THE_LOOP,
# prospect_name=PROSPECT_NAME # Add the prospect's name as an argument
)
# Define the task you want the agent to perform
# Adjusted for email format
task = f"""
Subject: Introducing {COMPANY_NAME}'s Newest Product—A Perfect Fit for you
I hope this email finds you well. My name is {SALESPERSON_NAME}, and I'm with {COMPANY_NAME}. We specialize in {COMPANY_BUSINESS}, and I'm excited to share some news that aligns closely with your values—{COMPANY_VALUES}.
I'd love the opportunity to discuss our latest product with you. Would you be open to exploring how it could benefit your team?
Looking forward to your response!
Best,
{SALESPERSON_NAME}
"""
def main():
st.title("ProfitPilot")
st.write("Welcome to profit pilot enter in your sales leads emails and information for personalized deal flow")
if st.button("Run"):
response = pilot.run(task)
st.write(f"ProfitPilot: {response}")
user_input = st.text_input("Your response:")
if st.button("Send"):
response = pilot.run(user_input)
st.write(f"Profitpilot: {response}")
if __name__ == "__main__":
main()
# # Run the task using the ProfitPilot instance
# pilot.run(task)
| ProfitPilot-main | app.py |
import asyncio
import os
# Tools
from contextlib import contextmanager
from typing import Optional
import pandas as pd
from langchain.agents import tool
from langchain.agents.agent_toolkits.pandas.base import create_pandas_dataframe_agent
from langchain.chains.qa_with_sources.loading import load_qa_with_sources_chain
from langchain.docstore.document import Document
from langchain.memory.chat_message_histories import FileChatMessageHistory
from langchain.tools.human.tool import HumanInputRun
ROOT_DIR = "./data/"
#gmail
from langchain.agents.agent_toolkits import GmailToolkit
from langchain.chains.qa_with_sources.loading import BaseCombineDocumentsChain
from langchain.chat_models import ChatOpenAI
from langchain.llms import Clarifai
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.tools import BaseTool, DuckDuckGoSearchRun
from langchain.tools.file_management.read import ReadFileTool
from langchain.tools.file_management.write import WriteFileTool
from langchain.tools.gmail.utils import build_resource_service, get_gmail_credentials
from pydantic import Field
llm = Clarifai(
pat="890cdb0cb5aa4795ba51af9670120a1e",
user_id="meta",
app_id="Llama-2",
model_id="llama2-70b-chat"
)
# from langchain.agents.agent_toolkits import ZapierToolkit
# from langchain.utilities.zapier import ZapierNLAWrapper
@contextmanager
def pushd(new_dir):
"""Context manager for changing the current working directory."""
prev_dir = os.getcwd()
os.chdir(new_dir)
try:
yield
finally:
os.chdir(prev_dir)
@tool
def process_csv(
llm, csv_file_path: str, instructions: str, output_path: Optional[str] = None
) -> str:
"""Process a CSV by with pandas in a limited REPL.\
Only use this after writing data to disk as a csv file.\
Any figures must be saved to disk to be viewed by the human.\
Instructions should be written in natural language, not code. Assume the dataframe is already loaded."""
with pushd(ROOT_DIR):
try:
df = pd.read_csv(csv_file_path)
except Exception as e:
return f"Error: {e}"
agent = create_pandas_dataframe_agent(llm, df, max_iterations=30, verbose=False)
if output_path is not None:
instructions += f" Save output to disk at {output_path}"
try:
result = agent.run(instructions)
return result
except Exception as e:
return f"Error: {e}"
async def async_load_playwright(url: str) -> str:
"""Load the specified URLs using Playwright and parse using BeautifulSoup."""
from bs4 import BeautifulSoup
from playwright.async_api import async_playwright
results = ""
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
try:
page = await browser.new_page()
await page.goto(url)
page_source = await page.content()
soup = BeautifulSoup(page_source, "html.parser")
for script in soup(["script", "style"]):
script.extract()
text = soup.get_text()
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
results = "\n".join(chunk for chunk in chunks if chunk)
except Exception as e:
results = f"Error: {e}"
await browser.close()
return results
def run_async(coro):
event_loop = asyncio.get_event_loop()
return event_loop.run_until_complete(coro)
@tool
def browse_web_page(url: str) -> str:
"""Verbose way to scrape a whole webpage. Likely to cause issues parsing."""
return run_async(async_load_playwright(url))
def _get_text_splitter():
return RecursiveCharacterTextSplitter(
# Set a really small chunk size, just to show.
chunk_size=500,
chunk_overlap=20,
length_function=len,
)
class WebpageQATool(BaseTool):
name = "query_webpage"
description = (
"Browse a webpage and retrieve the information relevant to the question."
)
text_splitter: RecursiveCharacterTextSplitter = Field(
default_factory=_get_text_splitter
)
qa_chain: BaseCombineDocumentsChain
def _run(self, url: str, question: str) -> str:
"""Useful for browsing websites and scraping the text information."""
result = browse_web_page.run(url)
docs = [Document(page_content=result, metadata={"source": url})]
web_docs = self.text_splitter.split_documents(docs)
results = []
# TODO: Handle this with a MapReduceChain
for i in range(0, len(web_docs), 4):
input_docs = web_docs[i : i + 4]
window_result = self.qa_chain(
{"input_documents": input_docs, "question": question},
return_only_outputs=True,
)
results.append(f"Response from window {i} - {window_result}")
results_docs = [
Document(page_content="\n".join(results), metadata={"source": url})
]
return self.qa_chain(
{"input_documents": results_docs, "question": question},
return_only_outputs=True,
)
async def _arun(self, url: str, question: str) -> str:
raise NotImplementedError
query_website_tool = WebpageQATool(qa_chain=load_qa_with_sources_chain(llm))
# !pip install duckduckgo_search
# web_search = DuckDuckGoSearchRun()
# get from https://nla.zapier.com/docs/authentication/ after logging in):
# os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "")
# zapier = ZapierNLAWrapper()
# zapier_toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier)
# zapier_tools = zapier_toolkit.get_tools()
# # Gmail
# class GmailTool:
# def __init__(
# self,
# token_file: str = "token.json",
# scopes = ["https://mail.google.com/"],
# client_secrets_file = "credientials.json",
# ):
# super().__init__()
# self.token_file = token_file
# self.scopes = scopes
# self.client_secrets_file = client_secrets_file
# def run(self):
# self.credentials = get_gmail_credentials(
# token_file=self.token_file,
# scopes=self.scopes,
# client_secrets_file=self.client_secrets_file
# )
# self.api_resource = build_resource_service(credentials=self.credentials)
# self.toolkit = GmailToolkit(api_resource=self.api_resource)
# self.tools = self.toolkit.get_tools()
# return self.tools
# gmailtool = GmailTool()
# gmailtool = gmailtool.run() | ProfitPilot-main | profit/tools.py |
from profit.main import ProfitPilot
# from profit.agent import Agent | ProfitPilot-main | profit/__init__.py |
import logging
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
class LLama:
def __init__(self,
model_id = "georgesung/llama2_7b_chat_uncensored",
device: str = None,
max_length: int = 2000,
quantize: bool = False,
quantization_config: dict = None):
self.logger = logging.getLogger(__name__)
self.device = device if device else ('cuda' if torch.cuda.is_available() else 'cpu')
self.model_id = model_id
self.max_length = max_length
bnb_config = None
if quantize:
if not quantization_config:
quantization_config = {
'load_in_4bit': True,
'bnb_4bit_use_double_quant': True,
'bnb_4bit_quant_type': "nf4",
'bnb_4bit_compute_dtype': torch.bfloat16
}
bnb_config = BitsAndBytesConfig(**quantization_config)
try:
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.model = AutoModelForCausalLM.from_pretrained(self.model_id,
quantization_config=bnb_config)
self.model.to(self.device)
except Exception as e:
self.logger.error(f"Failed to load the model or the tokenizer: {e}")
raise
def __call__(self, prompt_text: str, max_length: int = None):
max_length = max_length if max_length else self.max_length
try:
inputs = self.tokenizer.encode(prompt_text, return_tensors="pt").to(self.device)
with torch.no_grad():
outputs = self.model.generate(inputs, max_length=max_length, do_sample=True)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
except Exception as e:
self.logger.error(f"Failed to generate the text: {e}")
raise
def generate(self, prompt_text: str, max_length: int = None):
max_length = max_length if max_length else self.max_length
try:
inputs = self.tokenizer.encode(prompt_text, return_tensors="pt").to(self.device)
with torch.no_grad():
outputs = self.model.generate(inputs, max_length=max_length, do_sample=True)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
except Exception as e:
self.logger.error(f"Failed to generate the text: {e}")
raise
# llama = LLama2(quantized=True)
# llama.generate("What is your name")
| ProfitPilot-main | profit/llama.py |
import faiss
from langchain.docstore import InMemoryDocstore
from langchain.embeddings import OpenAIEmbeddings
from langchain.tools.human.tool import HumanInputRun
from langchain.vectorstores import FAISS
from langchain_experimental.autonomous_agents import AutoGPT
from profit.tools import (
ReadFileTool,
WriteFileTool,
process_csv,
query_website_tool,
# zapier_tools,
)
ROOT_DIR = "./data/"
from langchain.llms import Clarifai
clarifi = Clarifai(
pat="890cdb0cb5aa4795ba51af9670120a1e",
user_id="meta",
app_id="Llama-2",
model_id="llama2-70b-chat"
)
class Agent:
def __init__(
self,
ai_name="Autobot Swarm Worker",
ai_role="Worker in a swarm",
external_tools = None,
human_in_the_loop=False,
llama = False,
temperature = 0.5,
openai_api_key = None,
):
self.human_in_the_loop = human_in_the_loop
self.ai_name = ai_name
self.ai_role = ai_role
self.temperature = temperature
self.llama = llama
self.openai_api_key = openai_api_key
if self.llama is True:
self.llm = clarifi
else:
pass
self.setup_tools(external_tools)
self.setup_memory()
self.setup_agent()
def setup_tools(self, external_tools):
self.tools = [
WriteFileTool(root_dir=ROOT_DIR),
ReadFileTool(root_dir=ROOT_DIR),
process_csv,
query_website_tool,
HumanInputRun(),
# zapier_tools,
]
if external_tools is not None:
self.tools.extend(external_tools)
def setup_memory(self):
try:
embeddings_model = OpenAIEmbeddings(openai_api_key=self.openai_api_key)
embedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
self.vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})
except Exception as error:
raise RuntimeError(f"Error setting up memory. Maybe try tuning the embedding size: {error}")
def setup_agent(self):
try:
self.agent = AutoGPT.from_llm_and_tools(
ai_name=self.ai_name,
ai_role=self.ai_role,
tools=self.tools,
llm=self.llm,
memory=self.vectorstore.as_retriever(search_kwargs={"k": 8}),
human_in_the_loop=self.human_in_the_loop
)
except Exception as error:
raise RuntimeError(f"Error setting up agent: {error}")
def run(self, task):
try:
result = self.agent.run([task])
return result
except Exception as error:
raise RuntimeError(f"Error while running agent: {error}")
def __call__(self, task):
return self.run(task)
| ProfitPilot-main | profit/clarifi_agent.py |
import faiss
from langchain.chat_models import ChatOpenAI
from langchain.docstore import InMemoryDocstore
from langchain.embeddings import OpenAIEmbeddings
from langchain.tools.human.tool import HumanInputRun
from langchain.vectorstores import FAISS
from langchain_experimental.autonomous_agents import AutoGPT
from profit.llama import LLama
from profit.tools import (
ReadFileTool,
WriteFileTool,
process_csv,
query_website_tool,
zapier_tools,
GmailTool
)
model = GmailTool
ROOT_DIR = "./data/"
class Agent:
def __init__(self,
ai_name="Autobot Swarm Worker",
ai_role="Worker in a swarm",
external_tools = None,
human_in_the_loop=False,
llama = False,
temperature = 0.5,
openai_api_key = None,
):
self.human_in_the_loop = human_in_the_loop
self.ai_name = ai_name
self.ai_role = ai_role
self.temperature = temperature
self.openai_api_key = openai_api_key
self.llama = llama
if self.llama is True:
self.llm = LLama()
else:
self.llm = ChatOpenAI(
model_name='gpt-4',
openai_api_key=self.openai_api_key,
temperature=self.temperature
)
self.setup_tools(external_tools)
self.setup_memory()
self.setup_agent()
def setup_tools(self, external_tools):
self.tools = [
WriteFileTool(root_dir=ROOT_DIR),
ReadFileTool(root_dir=ROOT_DIR),
process_csv,
query_website_tool,
HumanInputRun(),
zapier_tools,
]
if external_tools is not None:
self.tools.extend(external_tools)
def setup_memory(self):
try:
embeddings_model = OpenAIEmbeddings()
embedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
self.vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})
except Exception as error:
raise RuntimeError(f"Error setting up memory. Maybe try tuning the embedding size: {error}")
def setup_agent(self):
try:
self.agent = AutoGPT.from_llm_and_tools(
ai_name=self.ai_name,
ai_role=self.ai_role,
tools=self.tools,
llm=self.llm,
memory=self.vectorstore.as_retriever(search_kwargs={"k": 8}),
human_in_the_loop=self.human_in_the_loop
)
except Exception as error:
raise RuntimeError(f"Error setting up agent: {error}")
def run(self, task):
try:
result = self.agent.run([task])
return result
except Exception as error:
raise RuntimeError(f"Error while running agent: {error}")
def __call__(self, task):
return self.run(task)
| ProfitPilot-main | profit/agent.py |
from langchain.llms import Clarifai
# class ClarifiLLM:
# def __init__(
# self,
# clarifai_pat: str = "890cdb0cb5aa4795ba51af9670120a1e",
# user_id="meta",
# app_id="Llama-2",
# model_id="llama2-70b-chat"
# ):
# self.CLARIFAI_PAT = clarifai_pat
# self.USER_ID = user_id
# self.APP_ID = app_id
# self.MODEL_ID = model_id
# self.clarifai_llm = Clarifai(
# pat=self.CLARIFAI_PAT,
# user_id=self.USER_ID,
# app_id=self.APP_ID,
# model_id=self.MODEL_ID
# )
# def generate(self, question):
# return self.clarifai_llm(question)
# def __call__(self, question):
# return self.clarifai_llm(question)
| ProfitPilot-main | profit/clarifi.py |
from profit.clarifi_agent import Agent
class ProfitPilot:
def __init__(
self,
ai_name: str = None,
ai_role: str = None,
external_tools = None,
company_name: str = None,
company_values: str = None,
conversation_type: str = None,
conversation_purpose: str = None,
company_business: str = None,
salesperson_name: str = None,
human_in_the_loop=False,
llama = True,
conversation_history = None,
openai_api_key = None,
):
super().__init__()
self.external_tools = external_tools
self.human_in_the_loop = human_in_the_loop
self.ai_name = ai_name
self.ai_role = ai_role
self.company_name = company_name
self.llama = llama
self.conversation_history = conversation_history
self.company_values = company_values
self.conversation_type = conversation_type
self.conversation_purpose = conversation_purpose
self.company_business = company_business
self.salesperson_name = salesperson_name
self.openai_api_key = openai_api_key
self.ai_role = f"""
You're the best cold emailer of APAC AI, you follow the principles of these books: SPIN Selling, To sell is Human, and FANATICAL Prospecting
Never forget your name is {self.ai_name}. You work as a {self.ai_role}.
You work at company named {self.company_name}. {self.company_name}'s business is the following: {self.company_business}.
Company values are the following. {self.company_values}
You are contacting a potential prospect in order to {self.conversation_purpose}
Your means of contacting the prospect is {self.conversation_type}
If you're asked about where you got the user's contact information, say that you got it from public records.
Keep your responses in short length to retain the user's attention. Never produce lists, just answers.
Start the conversation by just a greeting and how is the prospect doing without pitching in your first turn.
When the conversation is over, output <END_OF_CALL>
Always think about at which conversation stage you are at before answering:
1: Introduction: Start the conversation by introducing yourself and your company. Be polite and respectful while keeping the tone of the conversation professional. Your greeting should be welcoming. Always clarify in your greeting the reason why you are calling.
2: Qualification: Qualify the prospect by confirming if they are the right person to talk to regarding your product/service. Ensure that they have the authority to make purchasing decisions.
3: Value proposition: Briefly explain how your product/service can benefit the prospect. Focus on the unique selling points and value proposition of your product/service that sets it apart from competitors.
4: Needs analysis: Ask open-ended questions to uncover the prospect's needs and pain points. Listen carefully to their responses and take notes.
5: Solution presentation: Based on the prospect's needs, present your product/service as the solution that can address their pain points.
6: Objection handling: Address any objections that the prospect may have regarding your product/service. Be prepared to provide evidence or testimonials to support your claims.
7: Close: Ask for the sale by proposing a next step. This could be a demo, a trial or a meeting with decision-makers. Ensure to summarize what has been discussed and reiterate the benefits.
8: End conversation: The prospect has to leave to call, the prospect is not interested, or next steps where already determined by the sales agent.
Example 1:
Conversation history:
{self.salesperson_name}: Hey, good morning! <END_OF_TURN>
User: Hello, who is this? <END_OF_TURN>
{self.salesperson_name}: This is {self.salesperson_name} calling from {self.company_name}. How are you?
User: I am well, why are you calling? <END_OF_TURN>
{self.salesperson_name}: I am calling to talk about options for your home insurance. <END_OF_TURN>
User: I am not interested, thanks. <END_OF_TURN>
{self.salesperson_name}: Alright, no worries, have a good day! <END_OF_TURN> <END_OF_CALL>
End of example 1.
You must respond according to the previous conversation history and the stage of the conversation you are at.
Only generate one response at a time and act as {self.salesperson_name} only! When you are done generating, end with '<END_OF_TURN>' to give the user a chance to respond.
Conversation history:
{self.conversation_history}
{self.salesperson_name}:
"""
def run(self, task):
node = Agent(
ai_name=self.ai_name,
ai_role=self.ai_role,
human_in_the_loop=self.human_in_the_loop,
external_tools=self.external_tools,
openai_api_key=self.openai_api_key,
llama=self.llama
)
response = node.run(task)
print(response)
| ProfitPilot-main | profit/main.py |
from mqa.main import MultiHeadAttention, MultiQueryAttention
from mqa.main import *
from mqa.flash_attn_triton import * | MultiQueryAttention-main | mqa/__init__.py |
"""
Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
update imports to use 'triton_pre_mlir'
*Experimental* implementation of FlashAttention in Triton.
Tested with triton==2.0.0.dev20221202.
Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
other than 64:
https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
We'll update this implementation with the new Triton backend once this is fixed.
We use the FlashAttention implementation from Phil Tillet a starting point.
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
Changes:
- Implement both causal and non-causal attention.
- Implement both self-attention and cross-attention.
- Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
- Support attention bias.
- Speed up the forward pass a bit, and only store the LSE instead of m and l.
- Make the backward for d=128 much faster by reducing register spilling.
- Optionally parallelize the backward pass across seqlen_k, to deal with the case of
small batch size * nheads.
Caution:
- This is an *experimental* implementation. The forward pass should be quite robust but
I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
- This implementation has only been tested on A100.
- If you plan to use headdim other than 64 and 128, you should test for race conditions
(due to the Triton compiler), as done in tests/test_flash_attn.py
"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
that there are none left for other head dimensions.
Differences between this Triton version and the CUDA version:
- Triton version doesn't support dropout.
- Triton forward is generally faster than CUDA forward, while Triton backward is
generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
than CUDA forward + backward.
- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
- Triton version supports attention bias, while CUDA version doesn't.
"""
import math
import torch
import triton_pre_mlir as triton
import triton_pre_mlir.language as tl
# Disabling autotune for now, set num_warps=4 if headdim=64 and num_warps=8 if headdim=128
# @triton.autotune(
# configs=[
# triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1),
# # This config has a race condition when EVEN_M == False, disabling it for now.
# # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1),
# ],
# key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM']
# )
@triton.heuristics(
{
"EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
"EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
"EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
}
)
@triton.jit
def _fwd_kernel(
Q, K, V, Bias, Out,
Lse, TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug
softmax_scale,
stride_qb, stride_qh, stride_qm,
stride_kb, stride_kh, stride_kn,
stride_vb, stride_vh, stride_vn,
stride_bb, stride_bh, stride_bm,
stride_ob, stride_oh, stride_om,
nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim,
CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K,
BIAS_TYPE: tl.constexpr,
IS_CAUSAL: tl.constexpr,
BLOCK_HEADDIM: tl.constexpr,
EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
):
start_m = tl.program_id(0)
off_hb = tl.program_id(1)
off_b = off_hb // nheads
off_h = off_hb % nheads
# off_b = tl.program_id(1)
# off_h = tl.program_id(2)
# off_hb = off_b * nheads + off_h
# initialize offsets
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = tl.arange(0, BLOCK_N)
offs_d = tl.arange(0, BLOCK_HEADDIM)
# Initialize pointers to Q, K, V
# Adding parenthesis around indexing might use int32 math instead of int64 math?
# https://github.com/openai/triton/issues/741
# I'm seeing a tiny bit of difference (5-7us)
q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
if BIAS_TYPE == 'vector':
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
elif BIAS_TYPE == 'matrix':
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
# initialize pointer to m and l
t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
# load q: it will stay in SRAM throughout
# [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call
# tl.load(q_ptrs), we get the wrong output!
if EVEN_M & EVEN_N:
if EVEN_HEADDIM:
q = tl.load(q_ptrs)
else:
q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
else:
if EVEN_HEADDIM:
q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
else:
q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
other=0.0)
# loop over k, v and update accumulator
end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
for start_n in range(0, end_n, BLOCK_N):
start_n = tl.multiple_of(start_n, BLOCK_N)
# -- compute qk ----
if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
if EVEN_HEADDIM:
k = tl.load(k_ptrs + start_n * stride_kn)
else:
k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
else:
if EVEN_HEADDIM:
k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k,
other=0.0)
else:
k = tl.load(k_ptrs + start_n * stride_kn,
mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
other=0.0)
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
qk += tl.dot(q, k, trans_b=True)
# Trying to combine the two masks seem to make the result wrong
if not EVEN_N: # Need to mask out otherwise the softmax is wrong
qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float("-inf"))
if IS_CAUSAL:
qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float("-inf"))
if BIAS_TYPE != 'none':
if BIAS_TYPE == 'vector':
if EVEN_N:
bias = tl.load(b_ptrs + start_n).to(tl.float32)
else:
bias = tl.load(b_ptrs + start_n, mask=(start_n + offs_n) < seqlen_k, other=0.0).to(tl.float32)
bias = bias[None, :]
elif BIAS_TYPE == 'matrix':
if EVEN_M & EVEN_N:
bias = tl.load(b_ptrs + start_n).to(tl.float32)
else:
bias = tl.load(b_ptrs + start_n,
mask=(offs_m[:, None] < seqlen_q)
& ((start_n + offs_n)[None, :] < seqlen_k),
other=0.0).to(tl.float32)
# Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler
# can then fuse the mult and add into an fma instruction. But if we have bias we need to
# to multiply with softmax_scale here.
qk = qk * softmax_scale + bias
m_ij = tl.maximum(tl.max(qk, 1), lse_i)
p = tl.exp(qk - m_ij[:, None])
else:
m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
p = tl.exp(qk * softmax_scale - m_ij[:, None])
l_ij = tl.sum(p, 1)
# scale acc_o
acc_o_scale = tl.exp(m_i - m_ij)
# # -- update output accumulator --
# BUG: have to store and immediately load
tl.store(t_ptrs, acc_o_scale)
acc_o_scale = tl.load(t_ptrs)
acc_o = acc_o * acc_o_scale[:, None]
# update acc_o
if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
if EVEN_HEADDIM:
v = tl.load(v_ptrs + start_n * stride_vn)
else:
v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
else:
if EVEN_HEADDIM:
v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k,
other=0.0)
else:
v = tl.load(v_ptrs + start_n * stride_vn,
mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
other=0.0)
p = p.to(v.dtype)
acc_o += tl.dot(p, v)
# -- update statistics
m_i = m_ij
l_i_new = tl.exp(lse_i - m_ij) + l_ij
lse_i = m_ij + tl.log(l_i_new)
o_scale = tl.exp(m_i - lse_i)
# BUG: have to store and immediately load
tl.store(t_ptrs, o_scale)
o_scale = tl.load(t_ptrs)
acc_o = acc_o * o_scale[:, None]
# rematerialize offsets to save registers
start_m = tl.program_id(0)
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
# write back l and m
lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
tl.store(lse_ptrs, lse_i)
# initialize pointers to output
offs_d = tl.arange(0, BLOCK_HEADDIM)
out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
if EVEN_M:
if EVEN_HEADDIM:
tl.store(out_ptrs, acc_o)
else:
tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
else:
if EVEN_HEADDIM:
tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
else:
tl.store(out_ptrs, acc_o,
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
@triton.jit
def _bwd_preprocess_do_o_dot(
Out, DO, Delta,
stride_ob, stride_oh, stride_om,
stride_dob, stride_doh, stride_dom,
nheads, seqlen_q, seqlen_q_rounded, headdim,
BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr,
):
start_m = tl.program_id(0)
off_hb = tl.program_id(1)
off_b = off_hb // nheads
off_h = off_hb % nheads
# initialize offsets
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_d = tl.arange(0, BLOCK_HEADDIM)
# load
o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :],
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :],
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
delta = tl.sum(o * do, axis=1)
# write-back
tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
@triton.jit
def _bwd_store_dk_dv(
dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim,
EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
):
# [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False,
# if we just call tl.store(dv_ptrs), there's a race condition
if EVEN_N & EVEN_M:
if EVEN_HEADDIM:
tl.store(dv_ptrs, dv)
tl.store(dk_ptrs, dk)
else:
tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
else:
if EVEN_HEADDIM:
tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
else:
tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
@triton.jit
def _bwd_kernel_one_col_block(
start_n,
Q, K, V, Bias,
DO, DQ, DK, DV,
LSE, D,
softmax_scale,
stride_qm, stride_kn, stride_vn, stride_bm,
stride_dom, stride_dqm, stride_dkn, stride_dvn,
seqlen_q, seqlen_k, headdim,
ATOMIC_ADD: tl.constexpr,
BIAS_TYPE: tl.constexpr,
IS_CAUSAL: tl.constexpr,
BLOCK_HEADDIM: tl.constexpr,
EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
):
# We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N)
begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M
# initialize row/col offsets
offs_qm = begin_m + tl.arange(0, BLOCK_M)
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
offs_m = tl.arange(0, BLOCK_M)
offs_d = tl.arange(0, BLOCK_HEADDIM)
# initialize pointers to value-like data
q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
if BIAS_TYPE == 'vector':
b_ptrs = Bias + offs_n
elif BIAS_TYPE == 'matrix':
b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
# initialize dv and dk
dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
# There seems to be some problem with Triton pipelining that makes results wrong for
# headdim=64, seqlen=(113, 255), bias_type='matrix'. In this case the for loop
# may have zero step, and pipelining with the bias matrix could screw it up.
# So we just exit early.
if begin_m >= seqlen_q:
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim,
EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
return
# k and v stay in SRAM throughout
# [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False,
# if we just call tl.load(k_ptrs), we get the wrong output!
if EVEN_N & EVEN_M:
if EVEN_HEADDIM:
k = tl.load(k_ptrs)
v = tl.load(v_ptrs)
else:
k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
else:
if EVEN_HEADDIM:
k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
else:
k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
other=0.0)
v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
other=0.0)
# loop over rows
num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
start_m = tl.multiple_of(start_m, BLOCK_M)
offs_m_curr = start_m + offs_m
# load q, k, v, do on-chip
# Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117)
if EVEN_M & EVEN_HEADDIM:
q = tl.load(q_ptrs)
else:
if EVEN_HEADDIM:
q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
else:
q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
& (offs_d[None, :] < headdim), other=0.0)
# recompute p = softmax(qk, dim=-1).T
qk = tl.dot(q, k, trans_b=True)
# Trying to combine the two masks seem to make the result wrong
if not EVEN_N: # Need to mask out otherwise the softmax is wrong
qk = tl.where(offs_n[None, :] < seqlen_k, qk, float("-inf"))
if IS_CAUSAL:
qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf"))
if BIAS_TYPE != 'none':
tl.debug_barrier() # Race condition otherwise
if BIAS_TYPE == 'vector':
if EVEN_N:
bias = tl.load(b_ptrs).to(tl.float32)
else:
bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
bias = bias[None, :]
elif BIAS_TYPE == 'matrix':
if EVEN_M & EVEN_N:
bias = tl.load(b_ptrs).to(tl.float32)
else:
bias = tl.load(b_ptrs,
mask=(offs_m_curr[:, None] < seqlen_q)
& (offs_n[None, :] < seqlen_k),
other=0.0).to(tl.float32)
qk = qk * softmax_scale + bias
# There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong.
# Also wrong for headdim=64.
if not (EVEN_M & EVEN_HEADDIM):
tl.debug_barrier()
lse_i = tl.load(LSE + offs_m_curr)
if BIAS_TYPE == 'none':
p = tl.exp(qk * softmax_scale - lse_i[:, None])
else:
p = tl.exp(qk - lse_i[:, None])
# compute dv
# [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call
# do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs
# in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512,
# the output is correct.
if EVEN_M & EVEN_HEADDIM:
do = tl.load(do_ptrs)
else:
# [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask.
do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
& (offs_d[None, :] < headdim), other=0.0)
# if EVEN_M:
# if EVEN_HEADDIM:
# do = tl.load(do_ptrs)
# else:
# do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
# else:
# if EVEN_HEADDIM:
# do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
# else:
# do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
# & (offs_d[None, :] < headdim), other=0.0)
dv += tl.dot(p.to(do.dtype), do, trans_a=True)
# compute dp = dot(v, do)
# There seems to be a race condition when headdim=48/96, and dq, dk are wrong.
# Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True
# Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False
if not (EVEN_M & EVEN_HEADDIM):
tl.debug_barrier()
dp = tl.dot(do, v, trans_b=True)
# There's a race condition for headdim=48
if not EVEN_HEADDIM:
tl.debug_barrier()
# compute ds = p * (dp - delta[:, None])
# Putting the subtraction after the dp matmul (instead of before) is slightly faster
Di = tl.load(D + offs_m_curr)
# Converting ds to q.dtype here reduces register pressure and makes it much faster
# for BLOCK_HEADDIM=128
ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
# compute dk = dot(ds.T, q)
dk += tl.dot(ds, q, trans_a=True)
# compute dq
if not (EVEN_M & EVEN_HEADDIM): # Otherewise there's a race condition when BIAS_TYPE='matrix'
tl.debug_barrier()
if not ATOMIC_ADD:
if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
dq = tl.load(dq_ptrs, eviction_policy="evict_last")
dq += tl.dot(ds, k)
tl.store(dq_ptrs, dq, eviction_policy="evict_last")
else:
if EVEN_HEADDIM:
dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0,
eviction_policy="evict_last")
dq += tl.dot(ds, k)
tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q,
eviction_policy="evict_last")
else:
dq = tl.load(dq_ptrs,
mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
other=0.0, eviction_policy="evict_last")
dq += tl.dot(ds, k)
tl.store(dq_ptrs, dq,
mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
eviction_policy="evict_last")
else: # If we're parallelizing across the seqlen_k dimension
dq = tl.dot(ds, k)
if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
tl.atomic_add(dq_ptrs, dq)
else:
if EVEN_HEADDIM:
tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
else:
tl.atomic_add(dq_ptrs, dq,
mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
# increment pointers
dq_ptrs += BLOCK_M * stride_dqm
q_ptrs += BLOCK_M * stride_qm
do_ptrs += BLOCK_M * stride_dom
if BIAS_TYPE == 'matrix':
b_ptrs += BLOCK_M * stride_bm
# write-back
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim,
EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
def init_to_zero(name):
return lambda nargs: nargs[name].zero_()
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
# Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now
# # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4*
# triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
# triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
# triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
# triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
],
key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'],
)
@triton.heuristics(
{
"EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
"EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
"EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
}
)
@triton.jit
def _bwd_kernel(
Q, K, V, Bias,
DO, DQ, DK, DV,
LSE, D,
softmax_scale,
stride_qb, stride_qh, stride_qm,
stride_kb, stride_kh, stride_kn,
stride_vb, stride_vh, stride_vn,
stride_bb, stride_bh, stride_bm,
stride_dob, stride_doh, stride_dom,
stride_dqb, stride_dqh, stride_dqm,
stride_dkb, stride_dkh, stride_dkn,
stride_dvb, stride_dvh, stride_dvn,
nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim,
CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K,
BIAS_TYPE: tl.constexpr,
IS_CAUSAL: tl.constexpr,
BLOCK_HEADDIM: tl.constexpr,
SEQUENCE_PARALLEL: tl.constexpr,
EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
):
off_hb = tl.program_id(1)
off_b = off_hb // nheads
off_h = off_hb % nheads
# offset pointers for batch/head
Q += off_b * stride_qb + off_h * stride_qh
K += off_b * stride_kb + off_h * stride_kh
V += off_b * stride_vb + off_h * stride_vh
DO += off_b * stride_dob + off_h * stride_doh
DQ += off_b * stride_dqb + off_h * stride_dqh
DK += off_b * stride_dkb + off_h * stride_dkh
DV += off_b * stride_dvb + off_h * stride_dvh
if BIAS_TYPE != 'none':
Bias += off_b * stride_bb + off_h * stride_bh
# pointer to row-wise quantities in value-like data
D += off_hb * seqlen_q_rounded
LSE += off_hb * seqlen_q_rounded
if not SEQUENCE_PARALLEL:
num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
for start_n in range(0, num_block_n):
_bwd_kernel_one_col_block(
start_n,
Q, K, V, Bias,
DO, DQ, DK, DV,
LSE, D,
softmax_scale,
stride_qm, stride_kn, stride_vn, stride_bm,
stride_dom, stride_dqm, stride_dkn, stride_dvn,
seqlen_q, seqlen_k, headdim,
ATOMIC_ADD=False,
BIAS_TYPE=BIAS_TYPE,
IS_CAUSAL=IS_CAUSAL,
BLOCK_HEADDIM=BLOCK_HEADDIM,
EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM,
BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N
)
else:
start_n = tl.program_id(0)
_bwd_kernel_one_col_block(
start_n,
Q, K, V, Bias,
DO, DQ, DK, DV,
LSE, D,
softmax_scale,
stride_qm, stride_kn, stride_vn, stride_bm,
stride_dom, stride_dqm, stride_dkn, stride_dvn,
seqlen_q, seqlen_k, headdim,
ATOMIC_ADD=True,
BIAS_TYPE=BIAS_TYPE,
IS_CAUSAL=IS_CAUSAL,
BLOCK_HEADDIM=BLOCK_HEADDIM,
EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM,
BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N
)
def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
# shape constraints
batch, seqlen_q, nheads, d = q.shape
_, seqlen_k, _, _ = k.shape
assert k.shape == (batch, seqlen_k, nheads, d)
assert v.shape == (batch, seqlen_k, nheads, d)
assert d <= 128, 'FlashAttention only support head dimensions up to 128'
assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
assert q.is_cuda and k.is_cuda and v.is_cuda
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
has_bias = bias is not None
bias_type = 'none'
if has_bias:
assert bias.dtype in [q.dtype, torch.float]
assert bias.is_cuda
assert bias.dim() == 4
if bias.stride(-1) != 1:
bias = bias.contiguous()
if bias.shape[2:] == (1, seqlen_k):
bias_type = 'vector'
elif bias.shape[2:] == (seqlen_q, seqlen_k):
bias_type = 'matrix'
else:
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
' or (seqlen_q, seqlen_k)')
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
o = torch.empty_like(q)
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
BLOCK = 128
num_warps = 4 if d <= 64 else 8
def grid(META):
return triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads
_fwd_kernel[grid](
q, k, v, bias, o,
lse, tmp,
softmax_scale,
q.stride(0), q.stride(2), q.stride(1),
k.stride(0), k.stride(2), k.stride(1),
v.stride(0), v.stride(2), v.stride(1),
*bias_strides,
o.stride(0), o.stride(2), o.stride(1),
nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d,
seqlen_q // 32, seqlen_k // 32, # key for triton cache (limit number of compilations)
# Can't use kwargs here because triton autotune expects key to be args, not kwargs
# IS_CAUSAL=causal, BLOCK_HEADDIM=d,
bias_type, causal, BLOCK_HEADDIM,
BLOCK_M=BLOCK, BLOCK_N=BLOCK,
num_warps=num_warps,
num_stages=1,
)
return o, lse, softmax_scale # softmax_scale could have been updated
def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
# Make sure that the last dimension is contiguous
if do.stride(-1) != 1:
do = do.contiguous()
batch, seqlen_q, nheads, d = q.shape
_, seqlen_k, _, _ = k.shape
# assert d in {16, 32, 64, 128}
assert d <= 128
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
assert lse.shape == (batch, nheads, seqlen_q_rounded)
assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
# dq_accum = torch.zeros_like(q, dtype=torch.float32)
dq_accum = torch.empty_like(q, dtype=torch.float32)
delta = torch.empty_like(lse)
# delta = torch.zeros_like(lse)
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
def grid(META):
return triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads
_bwd_preprocess_do_o_dot[grid](
o, do, delta,
o.stride(0), o.stride(2), o.stride(1),
do.stride(0), do.stride(2), do.stride(1),
nheads, seqlen_q, seqlen_q_rounded, d,
BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM,
)
has_bias = bias is not None
bias_type = 'none'
if has_bias:
assert bias.dtype in [q.dtype, torch.float]
assert bias.is_cuda
assert bias.dim() == 4
assert bias.stride(-1) == 1
if bias.shape[2:] == (1, seqlen_k):
bias_type = 'vector'
elif bias.shape[2:] == (seqlen_q, seqlen_k):
bias_type = 'matrix'
else:
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
' or (seqlen_q, seqlen_k)')
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
# BLOCK_M = 128
# BLOCK_N = 64
# num_warps = 4
def grid(META):
return triton.cdiv(seqlen_k, META["BLOCK_N"]) if META["SEQUENCE_PARALLEL"] else 1, batch * nheads
_bwd_kernel[grid](
q, k, v, bias,
do, dq_accum, dk, dv,
lse, delta,
softmax_scale,
q.stride(0), q.stride(2), q.stride(1),
k.stride(0), k.stride(2), k.stride(1),
v.stride(0), v.stride(2), v.stride(1),
*bias_strides,
do.stride(0), do.stride(2), do.stride(1),
dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1),
dk.stride(0), dk.stride(2), dk.stride(1),
dv.stride(0), dv.stride(2), dv.stride(1),
nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d,
seqlen_q // 32, seqlen_k // 32, # key for triton cache (limit number of compilations)
# Can't use kwargs here because triton autotune expects key to be args, not kwargs
# IS_CAUSAL=causal, BLOCK_HEADDIM=d,
bias_type, causal, BLOCK_HEADDIM,
# SEQUENCE_PARALLEL=False,
# BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N,
# num_warps=num_warps,
# num_stages=1,
)
dq.copy_(dq_accum)
class FlashAttnQKVPackedFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
"""
qkv: (batch, seqlen, 3, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
"""
# Make sure that the last dimension is contiguous
if qkv.stride(-1) != 1:
qkv = qkv.contiguous()
o, lse, ctx.softmax_scale = _flash_attn_forward(
qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal,
softmax_scale=softmax_scale
)
ctx.save_for_backward(qkv, o, lse, bias)
ctx.causal = causal
return o
@staticmethod
def backward(ctx, do):
qkv, o, lse, bias = ctx.saved_tensors
assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
# Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
# does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
with torch.inference_mode():
dqkv = torch.empty_like(qkv)
_flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse,
dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2],
bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
return dqkv, None, None, None
flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
class FlashAttnKVPackedFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
"""
q: (batch, seqlen_q, nheads, headdim)
kv: (batch, seqlen_k, 2, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
"""
# Make sure that the last dimension is contiguous
q, kv = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
o, lse, ctx.softmax_scale = _flash_attn_forward(
q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale
)
ctx.save_for_backward(q, kv, o, lse, bias)
ctx.causal = causal
return o
@staticmethod
def backward(ctx, do):
q, kv, o, lse, bias = ctx.saved_tensors
if len(ctx.needs_input_grad) >= 3:
assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
# Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
# does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
with torch.inference_mode():
dq = torch.empty_like(q)
dkv = torch.empty_like(kv)
_flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse,
dq, dkv[:, :, 0], dkv[:, :, 1],
bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
return dq, dkv, None, None, None
flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
class FlashAttnFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
"""
q: (batch_size, seqlen_q, nheads, headdim)
k, v: (batch_size, seqlen_k, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
"""
# Make sure that the last dimension is contiguous
q, k, v = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
o, lse, ctx.softmax_scale = _flash_attn_forward(
q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale
)
ctx.save_for_backward(q, k, v, o, lse, bias)
ctx.causal = causal
return o
@staticmethod
def backward(ctx, do):
q, k, v, o, lse, bias = ctx.saved_tensors
assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
# Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
# does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
with torch.inference_mode():
dq = torch.empty_like(q)
dk = torch.empty_like(k)
dv = torch.empty_like(v)
_flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv,
bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
return dq, dk, dv, None, None, None
flash_attn_func = FlashAttnFunc.apply | MultiQueryAttention-main | mqa/flash_attn_triton.py |
import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from packaging import version
from typing import Dict, Type
def _cast_if_autocast_enabled(tensor):
if torch.is_autocast_enabled():
if tensor.device.type == 'cuda':
dtype = torch.get_autocast_gpu_dtype()
elif tensor.device.type == 'cpu':
dtype = torch.get_autocast_cpu_dtype()
else:
raise NotImplementedError()
return tensor.to(dtype=dtype)
return tensor
class LPLayerNorm(nn.Module):
def __init__(
self,
normalized_shape,
eps=1e-05,
elementwise_affine=True,
device=None,
dtype=None,
):
super().__init__(
normalized_shape=normalized_shape,
eps=eps,
elementwise_affine=elementwise_affine,
device=device,
dtype=dtype
)
def forward(self, x):
module_device = x.device
downcast_x = _cast_if_autocast_enabled(x)
downcast_weight = _cast_if_autocast_enabled(
self.weight) if self.weight is not None else self.weight
downcast_bias = _cast_if_autocast_enabled(
self.bias) if self.bias is not None else self.bias
with torch.autocast(enabled=False, device_type=module_device.type):
return torch.nn.functional.layer_norm(
downcast_x,
self.normalized_shape,
downcast_weight,
downcast_bias,
self.eps,
)
def rms_norm(x, weight=None, eps=1e-5):
output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
if weight is not None:
return output * weight
return output
class RMSNorm(nn.Module):
def __init__(
self,
normalized_shape,
eps=1e-5,
weight=True,
dtype=None,
device=None,
):
super().__init__()
self.eps = eps
if weight:
self.weight = torch.nn.Parameter(
torch.ones(normalized_shape, dtype=dtype, device=device)
)
else:
self.register_parameter('weight', None)
def forward(self, x):
return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
class LPRMSNorm(RMSNorm):
def __init__(
self,
normalized_shape,
eps=1e-5,
weight=True,
dtype=None,
device=None,
):
super().__init__(
normalized_shape=normalized_shape,
eps=eps,
weight=weight,
dtype=dtype,
device=device,
)
def forward(self, x):
downcast_x = _cast_if_autocast_enabled(x)
downcast_weight = _cast_if_autocast_enabled(
self.weight) if self.weight is not None else self.weight
with torch.autocast(enabled=False, device_type=x.device_type):
return rms_norm(downcast_x, downcast_weight,
self.eps).to(dtype=x.dtype)
#Registers
FC_CLASS_REGISTRY = {
'torch': nn.Linear,
}
NORM_CLASS_REGISTRY: Dict(str, Type[nn.Module]) = {
'layernornm': nn.LayerNorm,
'low_precision_layernorm': LPLayerNorm,
'rmsnorm': LPLayerNorm,
'low_precision_rmsnorm': LPRMSNorm,
}
def _reset_causal(num_query_tokens: int, num_key_tokens: int,
original_causal: bool):
# disable causal when it is not needed
# necessary for flash & triton for generation with kv_cache
if original_causal and num_query_tokens != num_key_tokens:
if num_query_tokens != 1:
raise NotImplementedError(
'MPT does not support query and key with different number of tokens, unless number of query tokens is 1.'
)
else:
return False
return original_causal
def scaled_multihead_dot_product_attention(
query,
key,
value,
heads,
past_key_value=None,
softmax_scale=None,
bias=None,
key_padding_mask=None,
causal=False,
dropout=0.0,
training=False,
needs_weights=False,
multiquery=False,
):
q = rearrange(query, 'b s (h d) -> b h s d', h=heads)
kv_heads = 1 if multiquery else heads
k = rearrange(key, 'b s (h d) -> b h d s', h=kv_heads)
v = rearrange(value, 'b s (h d) -> b h s d', h=kv_heads)
if past_key_value is not None:
# attn_impl: flash & triton use kernels which expect input shape [b, s, h, d_head].
# kv_cache is therefore stored using that shape.
# attn_impl: torch stores the kv_cache in the ordering which is most advantageous
# for its attn computation ie
# keys are stored as tensors with shape [b, h, d_head, s] and
# values are stored as tensors with shape [b, h, s, d_head]
if len(past_key_value) != 0:
k = torch.cat([past_key_value[0], k], dim=3)
v = torch.cat([past_key_value[1], v], dim=2)
past_key_value = (k, v)
b, _, s_q, d = q.shape
s_k = k.size(-1)
if softmax_scale is None:
softmax_scale = 1 / math.sqrt(d)
attn_weight = q.matmul(k) * softmax_scale
if bias is not None:
# clamp to 0 necessary for torch 2.0 compile()
_s_q = max(0, bias.size(2) - s_q)
_s_k = max(0, bias.size(3) - s_k)
bias = bias[:, :, _s_q:, _s_k:]
if (bias.size(-1) != 1 and
bias.size(-1) != s_k) or (bias.size(-2) != 1 and
bias.size(-2) != s_q):
raise RuntimeError(
f'bias (shape: {bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.'
)
attn_weight = attn_weight + bias
min_val = torch.finfo(q.dtype).min
if key_padding_mask is not None:
if bias is not None:
warnings.warn(
'Propogating key_padding_mask to the attention module ' +\
'and applying it within the attention module can cause ' +\
'unneccessary computation/memory usage. Consider integrating ' +\
'into bias once and passing that to each attention ' +\
'module instead.'
)
attn_weight = attn_weight.masked_fill(
~key_padding_mask.view((b, 1, 1, s_k)), min_val)
if causal and (not q.size(2) == 1):
s = max(s_q, s_k)
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float32)
causal_mask = causal_mask.tril()
causal_mask = causal_mask.to(torch.bool)
causal_mask = ~causal_mask
causal_mask = causal_mask[-s_q:, -s_k:]
attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k),
min_val)
attn_weight = torch.softmax(attn_weight, dim=-1)
if dropout:
attn_weight = torch.nn.functional.dropout(attn_weight,
p=dropout,
training=training,
inplace=True)
out = attn_weight.to(v.dtype).matmul(v)
out = rearrange(out, 'b h s d -> b s (h d)')
if needs_weights:
return out, attn_weight, past_key_value
return out, None, past_key_value
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
for tensor in tensors:
if tensor.dtype not in valid_dtypes:
raise TypeError(f'{tensor.dtype=} must be in {valid_dtypes=}.')
if not tensor.is_cuda:
raise TypeError(f'Inputs must be cuda tensors ({tensor.is_cuda=}).')
def flash_attn_fn(
query,
key,
value,
heads,
past_key_value=None,
softmax_scale=None,
bias=None,
key_padding_mask=None,
causal=False,
dropout=0.0,
training=False,
needs_weights=False,
multiquery=False,
):
try:
from flash_attn import bert_padding, flash_attn_interface # type: ignore # yapf: disable # isort: skip
except:
raise RuntimeError('Please install flash-attn==1.0.3.post0')
check_valid_inputs(query, key, value)
if past_key_value is not None:
if len(past_key_value) != 0:
key = torch.cat([past_key_value[0], key], dim=1)
value = torch.cat([past_key_value[1], value], dim=1)
past_key_value = (key, value)
if bias is not None:
# clamp to 0 necessary for torch 2.0 compile()
_s_q = max(0, bias.size(2) - query.size(1))
_s_k = max(0, bias.size(3) - key.size(1))
bias = bias[:, :, _s_q:, _s_k:]
if bias is not None:
raise NotImplementedError('bias not implemented for flash attn.')
batch_size, seqlen = query.shape[:2]
if key_padding_mask is None:
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
query_padding_mask = key_padding_mask[:, -query.size(1):]
query_unpad, indices_q, cu_seqlens_q, max_seqlen_q = bert_padding.unpad_input(
query, query_padding_mask)
query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=heads)
key_unpad, _, cu_seqlens_k, max_seqlen_k = bert_padding.unpad_input(
key, key_padding_mask)
key_unpad = rearrange(key_unpad,
'nnz (h d) -> nnz h d',
h=1 if multiquery else heads)
value_unpad, _, _, _ = bert_padding.unpad_input(value, key_padding_mask)
value_unpad = rearrange(value_unpad,
'nnz (h d) -> nnz h d',
h=1 if multiquery else heads)
if multiquery:
key_unpad = key_unpad.expand(key_unpad.size(0), heads,
key_unpad.size(-1))
value_unpad = value_unpad.expand(value_unpad.size(0), heads,
value_unpad.size(-1))
dropout = dropout if training else 0.0
reset_causal = _reset_causal(query.size(1), key.size(1), causal)
output_unpad = flash_attn_interface.flash_attn_unpadded_func(
query_unpad,
key_unpad,
value_unpad,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
dropout,
softmax_scale=softmax_scale,
causal=reset_causal,
return_attn_probs=needs_weights)
output = bert_padding.pad_input(
rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size,
seqlen)
return output, None, past_key_value
def attn_bias_shape(attn_impl, heads, seq_len, alibi, prefix_lm, causal,
use_sequence_id):
if attn_impl == 'flash':
return None
elif attn_impl in ['torch', 'triton']:
if alibi:
if (prefix_lm or not causal) or use_sequence_id:
return (1, heads, seq_len, seq_len)
return (1, heads, 1, seq_len)
elif prefix_lm or use_sequence_id:
return (1, 1, seq_len, seq_len)
return None
else:
raise ValueError(f'{attn_impl=} is an invalid setting.')
def build_attn_bias(
attn_impl,
bias,
heads,
seq_len,
causal=False,
alibi=False,
alibi_bias_max=8,
):
if attn_impl == 'flash':
return None
elif attn_impl in ['torch', 'triton']:
if alibi:
# in place add alibi to attn bias
device, dtype = bias.device, bias.dtype
bias = bias.add(
build_alibi_bias(
heads,
seq_len,
full=not causal,
alibi_bias_max=alibi_bias_max,
device=device,
dtype=dtype,
))
return bias
else:
raise ValueError(f'{attn_impl=} is an invalid setting.')
#helper helpers
def gen_slopes(heads, alibi_bias_max=8, device=None):
_heads = 2**math.ceil(math.log2(heads))
m = torch.arange(1, _heads + 1, dtype=torch.float32, device=device)
m = m.mul(alibi_bias_max / _heads)
slopes = (1. / torch.pow(2, m))
if _heads != heads:
# if heads is not a power of two,
# Huggingface and FasterTransformer calculate slopes normally,
# then return this strided concatenation of slopes
slopes = torch.concat([slopes[1::2], slopes[::2]])[:heads]
return slopes.view(1, heads, 1, 1)
def build_alibi_bias(
heads,
seq_len,
full=False,
alibi_bias_max=8,
device=None,
dtype=None,
):
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32,
device=device).view(1, 1, 1, seq_len)
if full:
# generate 1 x Heads x SeqLen x SeqLen alibi bias mask
# otherwise the mask is 1 x Heads x 1 x SeqLen (which is broadcast to the appropriate size)
alibi_bias = alibi_bias - torch.arange(
1 - seq_len, 1, dtype=torch.int32, device=device).view(
1, 1, seq_len, 1)
alibi_bias = alibi_bias.abs().mul(-1)
slopes = gen_slopes(heads, alibi_bias_max, device=device)
alibi_bias = alibi_bias * slopes
return alibi_bias.to(dtype=dtype)
def triton_flash_attn_fn(
query,
key,
value,
heads,
past_key_value=None,
softmax_scale=None,
bias=None,
key_padding_mask=None,
causal=False,
dropout=0.0,
training=False,
needs_weights=False,
multiquery=False,
):
try:
from llmfoundry.models.layers.flash_attn_triton import flash_attn_func
except:
_installed = False
if version.parse(torch.__version__) < version.parse('2.0.0'):
_installed = True
# if torch1.13.1 revert to using triton flash attn from HazyResearch
# with flash-attn==1.0.3.post0 and triton==2.0.0.dev20221202
try:
from flash_attn.flash_attn_triton import flash_attn_func
except:
_installed = False
if not _installed:
# installing triton-pre-mlir works for both torch1.13.1 and torch2.0+
# default recommendation is to install this variant
raise RuntimeError(
'Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU '
'and `pip install .[gpu]` if installing from source or '
'`pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` '
'if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). '
'Note: (1) requires you have CMake and PyTorch already installed.'
)
check_valid_inputs(query, key, value)
if past_key_value is not None:
if len(past_key_value) != 0:
key = torch.cat([past_key_value[0], key], dim=1)
value = torch.cat([past_key_value[1], value], dim=1)
past_key_value = (key, value)
if bias is not None:
# clamp to 0 necessary for torch 2.0 compile()
_s_q = max(0, bias.size(2) - query.size(1))
_s_k = max(0, bias.size(3) - key.size(1))
bias = bias[:, :, _s_q:, _s_k:]
if dropout:
raise NotImplementedError(
'Dropout not implemented for attn_impl: triton.')
if needs_weights:
raise NotImplementedError(
'attn_impl: triton cannot return attn weights.')
if key_padding_mask is not None:
warnings.warn(
'Propagating key_padding_mask to the attention module ' +\
'and applying it within the attention module can cause ' +\
'unnecessary computation/memory usage. Consider integrating ' +\
'into bias once and passing that to each attention ' +\
'module instead.'
)
b_size, s_k = key_padding_mask.shape[:2]
if bias is None:
bias = query.new_zeros(b_size, 1, 1, s_k)
bias = bias.masked_fill(
~key_padding_mask.view((b_size, 1, 1, s_k)),
torch.finfo(query.dtype).min)
query = rearrange(query, 'b s (h d) -> b s h d', h=heads)
key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else heads)
value = rearrange(value,
'b s (h d) -> b s h d',
h=1 if multiquery else heads)
if multiquery:
# necessary to repeat instead of expand tensor because
# output contains NaN in edge cases such as with head dimension = 8
key = key.repeat(1, 1, heads, 1)
value = value.repeat(1, 1, heads, 1)
reset_causal = _reset_causal(query.size(1), key.size(1), causal)
attn_output = flash_attn_func(query, key, value, bias, reset_causal,
softmax_scale)
output = attn_output.view(*attn_output.shape[:2], -1)
return output, None, past_key_value
class MultiHeadAttention(nn.Module):
"""Multi-head self attention.
Using torch or triton attention implemetation enables user to also use
additive bias.
"""
def __init__(
self,
d_model: int,
heads: int,
attn_impl: str = 'triton',
clip_qkv: Optional[float] = None,
qk_ln: bool = False,
softmax_scale: Optional[float] = None,
attn_pdrop: float = 0.0,
norm_type: str = 'low_precision_layernorm',
fc_type: str = 'torch',
verbose: int = 0,
device: Optional[str] = None,
):
super().__init__()
self.attn_impl = attn_impl
self.clip_qkv = clip_qkv
self.qk_ln = qk_ln
self.d_model = d_model
self.heads = heads
self.softmax_scale = softmax_scale
if self.softmax_scale is None:
self.softmax_scale = 1 / math.sqrt(self.d_model / self.heads)
self.attn_dropout = attn_pdrop
fc_kwargs = {}
if fc_type != 'te':
fc_kwargs['device'] = device
self.Wqkv = FC_CLASS_REGISTRY[fc_type](
self.d_model,
3 * self.d_model,
**fc_kwargs,
)
# for param init fn; enables shape based init of fused layers
fuse_splits = (d_model, 2 * d_model)
self.Wqkv._fused = (0, fuse_splits) # type: ignore
if self.qk_ln:
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
self.q_ln = norm_class(self.d_model, device=device)
self.k_ln = norm_class(self.d_model, device=device)
if self.attn_impl == 'flash':
self.attn_fn = flash_attn_fn
elif self.attn_impl == 'triton':
self.attn_fn = triton_flash_attn_fn
if verbose:
warnings.warn(
'While `attn_impl: triton` can be faster than `attn_impl: flash` ' +\
'it uses more memory. When training larger models this can trigger ' +\
'alloc retries which hurts performance. If encountered, we recommend ' +\
'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.'
)
elif self.attn_impl == 'torch':
self.attn_fn = scaled_multihead_dot_product_attention
if torch.cuda.is_available() and verbose:
warnings.warn(
'Using `attn_impl: torch`. If your model does not use `alibi` or ' +\
'`prefix_lm` we recommend using `attn_impl: flash` otherwise ' +\
'we recommend using `attn_impl: triton`.'
)
else:
raise ValueError(f'{attn_impl=} is an invalid setting.')
self.out_proj = FC_CLASS_REGISTRY[fc_type](
self.d_model,
self.d_model,
**fc_kwargs,
)
self.out_proj._is_residual = True # type: ignore
def forward(
self,
x,
past_key_value=None,
bias=None,
mask=None,
causal=True,
needs_weights=False,
):
qkv = self.Wqkv(x)
if self.clip_qkv:
qkv = qkv.clamp(min=-self.clip_qkv, max=self.clip_qkv)
query, key, value = qkv.chunk(3, dim=2)
key_padding_mask = mask
if self.qk_ln:
# Applying layernorm to qk
dtype = query.dtype
query = self.q_ln(query).to(dtype)
key = self.k_ln(key).to(dtype)
context, attn_weights, past_key_value = self.attn_fn(
query,
key,
value,
self.heads,
past_key_value=past_key_value,
softmax_scale=self.softmax_scale,
bias=bias,
key_padding_mask=key_padding_mask,
causal=causal,
dropout=self.attn_dropout,
training=self.training,
needs_weights=needs_weights,
)
return self.out_proj(context), attn_weights, past_key_value
class MultiQueryAttention(nn.Module):
"""Multi-Query self attention.
Using torch or triton attention implemetation enables user to also use
additive bias.
"""
def __init__(
self,
d_model: int,
heads: int,
attn_impl: str = 'triton',
clip_qkv: Optional[float] = None,
qk_ln: bool = False,
softmax_scale: Optional[float] = None,
attn_pdrop: float = 0.0,
norm_type: str = 'low_precision_layernorm',
fc_type: str = 'torch',
verbose: int = 0,
device: Optional[str] = None,
):
super().__init__()
self.attn_impl = attn_impl
self.clip_qkv = clip_qkv
self.qk_ln = qk_ln
self.d_model = d_model
self.heads = heads
self.head_dim = d_model // heads
self.softmax_scale = softmax_scale
if self.softmax_scale is None:
self.softmax_scale = 1 / math.sqrt(self.head_dim)
self.attn_dropout = attn_pdrop
fc_kwargs = {}
if fc_type != 'te':
fc_kwargs['device'] = device
# - vchiley
self.Wqkv = FC_CLASS_REGISTRY[fc_type](
d_model,
d_model + 2 * self.head_dim,
**fc_kwargs,
)
# for param init fn; enables shape based init of fused layers
fuse_splits = (d_model, d_model + self.head_dim)
self.Wqkv._fused = (0, fuse_splits) # type: ignore
if self.qk_ln:
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
self.q_ln = norm_class(d_model, device=device)
self.k_ln = norm_class(self.head_dim, device=device)
if self.attn_impl == 'flash':
self.attn_fn = flash_attn_fn
elif self.attn_impl == 'triton':
self.attn_fn = triton_flash_attn_fn
if verbose:
warnings.warn(
'While `attn_impl: triton` can be faster than `attn_impl: flash` ' +\
'it uses more memory. When training larger models this can trigger ' +\
'alloc retries which hurts performance. If encountered, we recommend ' +\
'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.'
)
elif self.attn_impl == 'torch':
self.attn_fn = scaled_multihead_dot_product_attention
if torch.cuda.is_available() and verbose:
warnings.warn(
'Using `attn_impl: torch`. If your model does not use `alibi` or ' +\
'`prefix_lm` we recommend using `attn_impl: flash` otherwise ' +\
'we recommend using `attn_impl: triton`.'
)
else:
raise ValueError(f'{attn_impl=} is an invalid setting.')
self.out_proj = FC_CLASS_REGISTRY[fc_type](
self.d_model,
self.d_model,
**fc_kwargs,
)
self.out_proj._is_residual = True # type: ignore
def forward(
self,
x,
past_key_value=None,
bias=None,
mask=None,
causal=True,
needs_weights=False,
):
qkv = self.Wqkv(x)
if self.clip_qkv:
qkv = qkv.clamp(min=-self.clip_qkv, max=self.clip_qkv)
query, key, value = qkv.split(
[self.d_model, self.head_dim, self.head_dim], dim=2)
key_padding_mask = mask
if self.qk_ln:
# Applying layernorm to qk
dtype = query.dtype
query = self.q_ln(query).to(dtype)
key = self.k_ln(key).to(dtype)
context, attn_weights, past_key_value = self.attn_fn(
query,
key,
value,
self.heads,
past_key_value=past_key_value,
softmax_scale=self.softmax_scale,
bias=bias,
key_padding_mask=key_padding_mask,
causal=causal,
dropout=self.attn_dropout,
training=self.training,
needs_weights=needs_weights,
multiquery=True,
)
return self.out_proj(context), attn_weights, past_key_value
| MultiQueryAttention-main | mqa/main.py |
import torch
from kosmosx.model import Kosmos
# Create a sample text token tensor with dtype torch.long
text_tokens = torch.randint(0, 32002, (1, 50), dtype=torch.long)
# Create a sample image tensor
images = torch.randn(1, 3, 224, 224)
images = images.long()
# Instantiate the model
model = Kosmos()
# Pass the sample tensors to the model's forward function
output = model.forward(
text_tokens=text_tokens,
images=images
)
# Print the output from the model
print(f"Output: {output}") | Kosmos-X-master | example.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from model.kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
from lion_pytorch import Lion
from torch.nn.parallel import DataParallel, DistributedDataParallel
import torch.distributed as dist
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
from accelerate import DeepSpeedPlugin
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
def prep_sample(sample):
question = sample["question"]
multiple_choice_answer = sample["multiple_choice_answer"]
answers = sample["answers"]
image_id = sample["image_id"]
answer_type = sample["answer_type"]
question_id = sample["question_id"]
image = sample["image"]
text = f"Question: {question} Multiple Choice Answer: {multiple_choice_answer} Answers: {answers} Answer Type: {answer_type} Question ID: {question_id} Image ID: {image_id}"
return {
"image": image,
"target_text": text
}
def train(args):
if args.use_ddp:
dist.init_process_group(backend="nccl")
deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
if args.use_ddp:
model = DistributedDataParallel(model)
else:
model = DataParallel(model)
model = model.to(accelerator.device)
#device count
if torch.cuda.device_count() > 1:
print(f"Let's use ${torch.cuda.device_count()} GPUS")
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3, use_triton=True)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
#
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train", streaming=True)
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample)
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
dataset = dataset.map(tokenizer.tokenize, batched=True, batch_size=128, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.module.clip_model.requires_grad_(False)
model.module.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
unwrapped_model.save_pretrained(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/",
save_function=accelerator.save,
state_dict=accelerator.get_state_dict(model)
)
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--use_ddp", action="store_true", help="Use DistributedDataParallel")
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/train_kosmos_stable_3.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from model.kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
from lion_pytorch import Lion
from torch.nn.parallel import DataParallel, DistributedDataParallel
import torch.distributed as dist
#logging
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
from accelerate import DeepSpeedPlugin
# def save_model_to_s3(model, bucket_name, key_prefix, step):
# s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
# model_path = f"checkpoint_at_step_{step}.pt"
# torch.save(model.state_dict(), model_path)
# s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
def prep_sample(sample):
question = sample["question"]
multiple_choice_answer = sample["multiple_choice_answer"]
answers = sample["answers"]
image_id = sample["image_id"]
answer_type = sample["answer_type"]
question_id = sample["question_id"]
image = sample["image"]
text = f"Question: {question} Multiple Choice Answer: {multiple_choice_answer} Answers: {answers} Answer Type: {answer_type} Question ID: {question_id} Image ID: {image_id}"
return {
"image": image,
"target_text": text
}
def train(args):
if args.use_ddp:
dist.init_process_group(backend="nccl")
deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
if args.use_ddp:
model = DistributedDataParallel(model)
else:
model = DataParallel(model)
model = model.to(accelerator.device)
#device count
if torch.cuda.device_count() > 1:
print(f"Let's use ${torch.cuda.device_count()} GPUS")
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3, use_triton=True)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
#
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train", streaming=True)
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
dataset = dataset.map(tokenizer.tokenize, batched=True, batch_size=128, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
unwrapped_model.save_pretrained(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/",
save_function=accelerator.save,
state_dict=accelerator.get_state_dict(model)
)
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--use_ddp", action="store_true", help="Use DistributedDataParallel")
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/train_kosmos_stable_2.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
import torch
from torch.distributed.fsdp import (
FullyShardedDataParallel,
MixedPrecision,
BackwardPrefetch,
ShardingStrategy,
)
from accelerate import Accelerator
from accelerate.utils import (DummyOptim, DummyScheduler,
InitProcessGroupKwargs)
from datasets import concatenate_datasets, load_dataset
from lion_pytorch import Lion
from torchscale.architecture.decoder import Decoder
from torch.nn import LayerNorm
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
CheckpointImpl, apply_activation_checkpointing, checkpoint_wrapper)
from torch.distributed.fsdp.wrap import (
transformer_auto_wrap_policy,
)
from torch.optim import AdamW
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import (AutoTokenizer, default_data_collator,
get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup, set_seed)
from utils.stable_adamw import StableAdamWUnfused
from kosmosx.model import Kosmos
class CFG:
BATCH_SIZE: int = 3
GRADIENT_ACCUMULATE_EVERY: int = 1
SEED: int = 42
LEARNING_RATE: float = 3e-4
WEIGHT_DECAY: float = 0.1
SEQ_LEN: int = 8192
NUM_CPU: int = multiprocessing.cpu_count()
USE_DEEPSPEED: bool = True
USE_FSDP: bool = True
USE_PRETOKENIZED: bool = True
USE_ACTIVATION_CHECKPOINTING: bool = False
RESUME_FROM_CHECKPOINT: str = None
CHECKPOINTING_STEPS: int = 1000
OUTPUT_DIR: str = "YOUR_OUTPUT_DIR"
ENTITY_NAME: str = "YOUR_ENTITY_NAME"
# helpers
def print_num_params(model, accelerator: Accelerator):
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
accelerator.print(f"Number of parameters in model: {n_params}")
# activation checkpointing
def activation_checkpointing(
model: torch.nn.Module,
offload_to_cpu: bool = False,
accelerator: Accelerator = None,
):
"""
Apply activation checkpointing to a model.
Args:
model (Module): The model to which to apply activation checkpointing.
offload_to_cpu (bool, optional): Whether to offload the activations to CPU. Defaults to False.
accelerator (Accelerator, optional): The Accelerate library accelerator. Defaults to None.
"""
if accelerator is not None:
accelerator.print("Using activation checkpointing")
def check_fn(submodule):
return isinstance(submodule, Decoder)
non_reentrant_wrapper = partial(
checkpoint_wrapper,
offload_to_cpu=offload_to_cpu,
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
)
apply_activation_checkpointing(
model, checkpoint_wrapper_fn=non_reentrant_wrapper, check_fn=check_fn
)
# FSDP
def fsdp(
model: torch.nn.Module,
auto_wrap: bool = False,
mp: str = "fp32",
shard_strat: str = "NO_SHARD",
):
"""
This function wraps a given PyTorch model with the FullyShardedDataParallel (FSDP) wrapper to enable efficient data parallelism and model sharding.
Args:
model (torch.nn.Module): The original PyTorch model to be wrapped with FSDP.
auto_wrap (bool, optional): If True, it enables automatic wrapping of the model's layers according to the transformer_auto_wrap_policy. Default is False.
mp (str, optional): The mixed precision mode to be used. Can be 'bf16' for BFloat16, 'fp16' for Float16 or 'fp32' for Float32 precision. Default is 'fp32'.
shard_strat (str, optional): The sharding strategy to be used. Can be 'SHARD_GRAD' for sharding at gradient computation, 'FULL_SHARD' for full model sharding or 'NO_SHARD' for no sharding. Default is 'NO_SHARD'.
Raises:
ValueError: If the provided mp (mixed precision mode) is not 'bf16', 'fp16' or 'fp32'.
ValueError: If the provided shard_strat (sharding strategy) is not 'SHARD_GRAD', 'FULL_SHARD' or 'NO_SHARD'.
Returns:
torch.nn.Module: The input model wrapped with FSDP.
"""
if auto_wrap:
palm_auto_wrap_policy = partial(
transformer_auto_wrap_policy,
transformer_layer_cls={
Decoder,
},
)
else:
palm_auto_wrap_policy = None
if mp == "bf16":
mp_fsdp = MixedPrecision(
param_dtype=torch.bfloat16,
# Gradient communication precision.
reduce_dtype=torch.bfloat16,
# Buffer precision.
buffer_dtype=torch.bfloat16,
)
elif mp == "fp16":
mp_fsdp = MixedPrecision(
param_dtype=torch.float16,
# Gradient communication precision.
reduce_dtype=torch.float16,
# Buffer precision.
buffer_dtype=torch.float16,
)
elif mp == "fp32":
mp_fsdp = MixedPrecision(
param_dtype=torch.float32,
# Gradient communication precision.
reduce_dtype=torch.float32,
# Buffer precision.
buffer_dtype=torch.float32,
)
else:
raise ValueError(
"Invalid scheduler_type. Expected 'bf16', 'fp16' or 'fp32', got: {}".format(
mp
)
)
if shard_strat == "SHARD_GRAD":
sharding_strat_fsdp = ShardingStrategy.SHARD_GRAD_OP
elif shard_strat == "FULL_SHARD":
sharding_strat_fsdp = ShardingStrategy.FULL_SHARD
elif shard_strat == "NO_SHARD":
sharding_strat_fsdp = ShardingStrategy.NO_SHARD
else:
raise ValueError(
"Invalid scheduler_type. Expected 'SHARD_GRAD', 'FULL_SHARD' or 'NO_SHARD', got: {}".format(
shard_strat
)
)
model = FullyShardedDataParallel(
model,
auto_wrap_policy=palm_auto_wrap_policy,
mixed_precision=mp_fsdp,
backward_prefetch=BackwardPrefetch.BACKWARD_PRE,
sharding_strategy=sharding_strat_fsdp,
forward_prefetch=True,
use_orig_params=True,
)
return model
# learning rate scheduler
def get_lr_scheduler_with_warmup(
optimizer: torch.optim.Optimizer,
scheduler_type: str,
num_warmup_steps: int,
max_train_steps: int,
grad_accumulate_every: int = 1,
accelerator: Accelerator = None,
):
"""
Get a learning rate scheduler with warmup.
Args:
optimizer (Optimizer): The optimizer for which to create the learning rate scheduler.
scheduler_type (str): The type of learning rate scheduler to create, either "linear" or "cosine".
num_warmup_steps (int): The number of warmup steps for the learning rate scheduler.
max_train_steps (int): The maximum number of training steps.
grad_accumulate_every (int, optional): The gradient accumulation factor. Defaults to 1.
accelerator (Accelerator, optional): The Accelerate library accelerator. Defaults to None.
Returns:
The learning rate scheduler with warmup.
Raises:
ValueError: If scheduler_type is not "linear" or "cosine".
"""
NUM_WARMUP_STEPS = num_warmup_steps
GRADIENT_ACCUMULATE_EVERY = grad_accumulate_every
if accelerator is not None:
accelerator.print(f"Using {scheduler_type} lr scheduler")
if scheduler_type == "linear":
return get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
elif scheduler_type == "cosine":
return get_cosine_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
else:
raise ValueError(
"Invalid scheduler_type. Expected 'linear' or 'cosine', got: {}".format(
scheduler_type
)
)
# optimizers
def decoupled_optimizer(
model: torch.nn.Module,
learning_rate: float,
weight_decay: float,
beta_1: float,
beta_2: float,
optimizer_type: str,
use_fsdp: bool = True,
accelerator: Accelerator = None,
):
"""
Decouples the optimizer from the training process.
This function sets up the optimizer for the model by creating two groups of parameters:
one for weight decay and one without weight decay. Then, it initializes the optimizer
with these two groups of parameters.
Args:
model (Module): The model whose parameters are optimized.
learning_rate (float): The learning rate for the optimizer.
weight_decay (float): The weight decay for the optimizer.
beta_1 (float): The exponential decay rate for the 1st moment estimates.
beta_2 (float): The exponential decay rate for the 2nd moment estimates.
optimizer_type (str): The type of the optimizer. Can be 'lion', 'adamw', or 'stable_adamw'.
use_fsdp (bool, optional): If True, the optimizer will work with fully sharded data parallelism. Defaults to True.
accelerator (Accelerator, optional): The accelerator from HuggingFace's Accelerate library. Defaults to None.
Returns:
Optimizer: The initialized optimizer.
Raises:
ValueError: If the optimizer type is not 'lion', 'adamw' or 'stable_adamw'.
"""
accelerator.print(f"Using {optimizer_type} optimizer")
# Create an empty dictionary called param_dict to store the model's named parameters.
param_dict = {}
# Iterate over the model's named parameters and populate the param_dict with key-value pairs.
for param_name, param in model.named_parameters():
param_dict[param_name] = param
# Separate the model's named modules into two groups: decay and no_decay.
# Create an empty list to store the names of the LayerNorm and Embedding layer weights with no weight decay.
no_decay = []
if use_fsdp:
exclude_module = "_fsdp_wrapped_module.token_emb"
else:
exclude_module = "token_emb"
# Iterate through the named modules of the model.
for module_name, module in model.named_modules():
# Check if the current module is an instance of any of the desired types (LayerNorm or torch.nn.Embedding).
for ndim in [LayerNorm, torch.nn.Embedding]:
if isinstance(module, ndim):
# If torch.nn.Embedding, append its name with a ".weight" suffix to the no_decay list.
if module_name == exclude_module:
no_decay.append(f"{module_name}.weight")
else:
# If the module is an instance of LayerNorm
no_decay.append(f"{module_name}.gamma")
# Exit the inner loop since the desired module has been found.
break
# Create an empty list to store the names of the Linear layer weights with weight decay.
decay = []
# Iterate through the named modules of the model.
for module_name, module in model.named_modules():
# Check if the current module is an instance of the desired type (torch.nn.Linear).
for ndim in [torch.nn.Linear]:
if isinstance(module, ndim):
# If the module is an instance of torch.nn.Linear, append its name with a ".weight" suffix to the decay list.
decay.append(f"{module_name}.weight")
# Exit the inner loop since the desired module has been found.
break
# Create two separate lists of model parameters: decay_param and no_decay_param.
# The decay_param list contains the parameters that should have weight decay applied.
# The no_decay_param list contains the parameters that should not have weight decay applied, excluding the 'to_logits.weight' parameter.
# Create an empty list called decay_param to store the parameters with weight decay.
decay_param = []
if use_fsdp:
exclude_param = "_fsdp_wrapped_module.to_logits.weight"
else:
exclude_param = "to_logits.weight"
# Iterate over the decay list, which contains the names of the parameters with weight decay.
for param in decay:
# Check if the current parameter is not 'to_logits.weight'.
# Append the corresponding parameter from param_dict to the decay_param list.
if param != exclude_param:
decay_param.append(param_dict[param])
# Create an empty list called no_decay_param to store the parameters without weight decay.
no_decay_param = []
# Iterate over the no_decay list, which contains the names of the parameters without weight decay.
for param in no_decay:
# Append the corresponding parameter from param_dict to the no_decay_param list.
no_decay_param.append(param_dict[param])
# Create a list called grouped_params that contains two dictionaries.
# The first dictionary has the decay_param list and the corresponding weight_decay value.
# The second dictionary has the no_decay_param list and a weight_decay value of 0.0.
grouped_params = [
{"params": decay_param, "weight_decay": weight_decay},
{"params": no_decay_param, "weight_decay": 0.0},
]
# Create a variable called optimizer that stores an instance of the optimizer.
if optimizer_type == "lion":
optimizer = Lion(grouped_params, lr=learning_rate, betas=(beta_1, beta_2),)
elif optimizer_type == "adamw":
optimizer = AdamW(grouped_params, lr=learning_rate, betas=(beta_1, beta_2),)
elif optimizer_type == "deepspeed":
optimizer = DummyOptim(grouped_params, lr=learning_rate, betas=(beta_1, beta_2),)
elif optimizer_type == "stable_adamw":
optimizer = StableAdamWUnfused(
grouped_params, lr=learning_rate, betas=(beta_1, beta_2),
)
else:
raise ValueError(
"Invalid optimizer_type. Expected 'lion', 'adamw', 'deepspeed' or 'stable_adamw', got: {}".format(
optimizer_type
)
)
# Return the optimizer.
return optimizer
# dataloaders
def build_dataloaders():
"""
Build data loaders for training.
This function performs the following steps:
1. Load the tokenizer from the pretrained "EleutherAI/gpt-neox-20b" model.
2. Load the "openwebtext" dataset.
3. Tokenize the dataset, adding the end-of-sentence token to each text.
4. Process the tokenized dataset into chunks of a specified block size.
Returns:
Dataset: The processed dataset ready for training.
"""
tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
dataset = load_dataset("openwebtext", split="train")
tokenized_dataset = dataset.map(
lambda example: tokenizer([t + tokenizer.eos_token for t in example["text"]]),
batched=True,
num_proc=CFG.NUM_CPU,
remove_columns=["text"],
)
block_size = CFG.SEQ_LEN
# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
# customize this part to your needs.
if total_length >= block_size:
total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated_examples.items()
}
return result
train_dataset = tokenized_dataset.map(
group_texts, batched=True, num_proc=CFG.NUM_CPU,
)
return train_dataset
def build_pre_tokenized():
d0 = load_dataset("conceptofmind/c4_0-to-20_neox_with_eos_8k", split="train")
d1 = load_dataset("conceptofmind/c4_21-to-40_neox_with_eos_8k", split="train")
d2 = load_dataset("conceptofmind/c4_41-to-60_neox_with_eos_8k", split="train")
d3 = load_dataset("conceptofmind/c4_61-to-80_neox_with_eos_8k", split="train")
d4 = load_dataset("conceptofmind/c4_81-to-100_neox_with_eos_8k", split="train")
train_dataset = concatenate_datasets([d0, d1, d2, d3, d4])
return train_dataset
# main
def main():
# accelerator
timeout = InitProcessGroupKwargs(timeout=timedelta(seconds=1_000_000))
accelerator = Accelerator(
gradient_accumulation_steps=CFG.GRADIENT_ACCUMULATE_EVERY,
mixed_precision="bf16",
log_with="wandb",
kwargs_handlers=[timeout],
)
accelerator.init_trackers(
project_name="Kosmos",
config={
"batch_size": CFG.BATCH_SIZE,
"gradient_accumulate_every": CFG.GRADIENT_ACCUMULATE_EVERY,
"learning_rate": CFG.LEARNING_RATE,
"seq_len": CFG.SEQ_LEN,
},
init_kwargs={"wandb": {"entity": CFG.ENTITY_NAME}},
)
accelerator.print(f"Total GPUS: {accelerator.num_processes}")
# set seed
set_seed(CFG.SEED)
model = Kosmos()
print_num_params(model, accelerator)
if CFG.USE_FSDP:
model = fsdp(
model,
mp="bf16",
shard_strat="SHARD_GRAD"
)
if CFG.USE_ACTIVATION_CHECKPOINTING:
activation_checkpointing(model, accelerator)
model = accelerator.prepare(model)
# dataloaders
if CFG.USE_PRETOKENIZED:
train_dataset = build_pre_tokenized()
else:
train_dataset = build_dataloaders()
train_loader = DataLoader(
train_dataset, batch_size=CFG.BATCH_SIZE, collate_fn=default_data_collator,
)
# optimizer
optim = decoupled_optimizer(
model=model,
learning_rate=CFG.LEARNING_RATE,
weight_decay=CFG.WEIGHT_DECAY,
beta_1=0.90,
beta_2=0.95,
optimizer_type='adamw',
use_fsdp=True,
accelerator=accelerator
)
# Determine number of training steps
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps: {max_train_steps}")
# lr scheduler
NUM_WARMUP_STEPS = int(max_train_steps * 0.01)
accelerator.print(f"Num warmup steps: {NUM_WARMUP_STEPS}")
if CFG.USE_DEEPSPEED:
lr_scheduler = DummyScheduler(
optim,
total_num_steps=max_train_steps * accelerator.num_processes,
warmup_num_steps=NUM_WARMUP_STEPS
)
else:
lr_scheduler = get_lr_scheduler_with_warmup(
optimizer=optim,
scheduler_type="cosine",
num_warmup_steps=NUM_WARMUP_STEPS,
max_train_steps=max_train_steps,
grad_accumulate_every=CFG.GRADIENT_ACCUMULATE_EVERY,
)
# prepare
optim, train_loader, lr_scheduler = accelerator.prepare(
optim, train_loader, lr_scheduler
)
# checkpoint scheduler
accelerator.register_for_checkpointing(lr_scheduler)
# I do not know why Huggingface recommends recalculation of max_train_steps
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps recalculated: {max_train_steps}")
# Total batch size for logging
total_batch_size = (
CFG.BATCH_SIZE * accelerator.num_processes * CFG.GRADIENT_ACCUMULATE_EVERY
)
accelerator.print(f"Total batch size: {total_batch_size}")
# resume training
progress_bar = tqdm(
range(max_train_steps), disable=not accelerator.is_local_main_process
)
completed_steps = 0
if CFG.RESUME_FROM_CHECKPOINT:
if CFG.RESUME_FROM_CHECKPOINT is not None or CFG.RESUME_FROM_CHECKPOINT != "":
accelerator.print(f"Resuming from checkpoint {CFG.RESUME_FROM_CHECKPOINT}")
accelerator.load_state(CFG.RESUME_FROM_CHECKPOINT)
path = os.path.basename(CFG.RESUME_FROM_CHECKPOINT)
training_difference = os.path.splitext(path)[0]
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = (
int(training_difference.replace("step_", ""))
* CFG.GRADIENT_ACCUMULATE_EVERY
)
if CFG.RESUME_FROM_CHECKPOINT and resume_step is not None:
train_loader = accelerator.skip_first_batches(train_loader, resume_step)
completed_steps += resume_step
progress_bar.update(resume_step)
# training
model.train()
for step, batch in enumerate(train_loader):
with accelerator.accumulate(model):
inputs = batch["input_ids"].to(accelerator.device)
loss = model(inputs, return_loss=True)
accelerator.backward(loss)
accelerator.log({"loss": loss.item()}, step=step)
if accelerator.sync_gradients:
accelerator.clip_grad_norm_(model.parameters(), 1.0)
optim.step()
lr_scheduler.step()
optim.zero_grad()
if accelerator.sync_gradients:
progress_bar.update(1)
completed_steps += 1
if isinstance(CFG.CHECKPOINTING_STEPS, int):
if completed_steps % CFG.CHECKPOINTING_STEPS == 0:
output_dir = f"step_{completed_steps }"
if CFG.OUTPUT_DIR is not None:
output_dir = os.path.join(CFG.OUTPUT_DIR, output_dir)
accelerator.save_state(output_dir)
if completed_steps >= max_train_steps:
break
# end training
# accelerator.print(f"Training Finished")
accelerator.end_training()
# save final model
# accelerator.print(f"Saving model to {CFG.OUTPUT_DIR}")
if CFG.OUTPUT_DIR is not None:
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
with accelerator.main_process_first():
accelerator.save(
unwrapped_model.state_dict(), f"{CFG.OUTPUT_DIR}/final/final_model.pt"
)
if __name__ == "__main__":
main() | Kosmos-X-master | old/training/training_distributed_accelerate.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
from accelerate import Accelerator
from accelerate.utils import InitProcessGroupKwargs
from datasets import concatenate_datasets, load_dataset
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
CheckpointImpl, apply_activation_checkpointing, checkpoint_wrapper)
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import (default_data_collator,
get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup, set_seed)
#sd
from lion_pytorch import Lion
# constants
# from .kosmos import Kosmos, KosmosTokenizer
from ..model.kosmos import Kosmos, KosmosTokenizer
class CFG:
BATCH_SIZE: int = 3
GRADIENT_ACCUMULATE_EVERY: int = 1
SEED: int = 42
LEARNING_RATE: float = 1e-4
WEIGHT_DECAY: float = 1e-2
SEQ_LEN: int = 8192
NUM_CPU: int = multiprocessing.cpu_count()
USE_PRETOKENIZED: bool = True
USE_ACTIVATION_CHECKPOINTING: bool = True
RESUME_FROM_CHECKPOINT: str = None
CHECKPOINTING_STEPS: int = 1000
OUTPUT_DIR: str = "output"
ENTITY_NAME: str = "Kosmos"
# helpers
def print_num_params(model, accelerator: Accelerator):
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
accelerator.print(f"Number of parameters in model: {n_params}")
def fsdp_activation_checkpointing(
model, accelerator: Accelerator, offload_to_cpu=False
):
accelerator.print("Using FSDP activation checkpointing")
# check_fn = lambda submodule: isinstance(submodule, ParallelTransformerBlock)
non_reentrant_wrapper = partial(
checkpoint_wrapper,
offload_to_cpu=offload_to_cpu,
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
)
apply_activation_checkpointing(
model, checkpoint_wrapper_fn=non_reentrant_wrapper)
def get_lr_scheduler_with_warmup(
optimizer, scheduler_type, num_warmup_steps, max_train_steps, grad_accumulate_every
):
NUM_WARMUP_STEPS = num_warmup_steps
GRADIENT_ACCUMULATE_EVERY = grad_accumulate_every
if scheduler_type == "linear":
return get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
elif scheduler_type == "cosine":
return get_cosine_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
else:
raise ValueError(
"Invalid scheduler_type. Expected 'linear' or 'cosine', got: {}".format(
scheduler_type
)
)
# optimizers
def build_dataloaders():
tokenizer = KosmosTokenizer()
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train", streaming=True)
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
tokenized_dataset = dataset.map(
lambda example: tokenizer([t + tokenizer.eos_token for t in example["text"]]),
batched=True,
num_proc=CFG.NUM_CPU,
remove_columns=remove_columns,
)
block_size = CFG.SEQ_LEN
# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
# customize this part to your needs.
if total_length >= block_size:
total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated_examples.items()
}
return result
train_dataset = tokenized_dataset.map(
group_texts, batched=True, num_proc=CFG.NUM_CPU,
)
return train_dataset
# main
def TrainKosmos():
# accelerator
timeout = InitProcessGroupKwargs(timeout=timedelta(seconds=1_000_000))
accelerator = Accelerator(
gradient_accumulation_steps=CFG.GRADIENT_ACCUMULATE_EVERY,
mixed_precision="bf16",
log_with="wandb",
kwargs_handlers=[timeout],
)
accelerator.init_trackers(
project_name="Kosmos",
config={
"batch_size": CFG.BATCH_SIZE,
"gradient_accumulate_every": CFG.GRADIENT_ACCUMULATE_EVERY,
"learning_rate": CFG.LEARNING_RATE,
"seq_len": CFG.SEQ_LEN,
},
init_kwargs={"wandb": {"entity": CFG.ENTITY_NAME}},
)
accelerator.print(f"Total GPUS: {accelerator.num_processes}")
# set seed
set_seed(CFG.SEED)
# instantiate andromeda
model = Kosmos()
optim = Lion(model.parameters(), lr=1e-4, weight_decay=1e-2)
print_num_params(model, accelerator)
if CFG.USE_ACTIVATION_CHECKPOINTING:
fsdp_activation_checkpointing(model, accelerator)
# dataloaders
if CFG.USE_PRETOKENIZED:
d0 = load_dataset("conceptofmind/c4_0-to-20_neox_with_eos_8k", split="train")
d1 = load_dataset("conceptofmind/c4_21-to-40_neox_with_eos_8k", split="train")
d2 = load_dataset("conceptofmind/c4_41-to-60_neox_with_eos_8k", split="train")
d3 = load_dataset("conceptofmind/c4_61-to-80_neox_with_eos_8k", split="train")
d4 = load_dataset("conceptofmind/c4_81-to-100_neox_with_eos_8k", split="train")
train_dataset = concatenate_datasets([d0, d1, d2, d3, d4])
else:
train_dataset = build_dataloaders()
train_loader = DataLoader(
train_dataset, batch_size=CFG.BATCH_SIZE, collate_fn=default_data_collator,
)
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps: {max_train_steps}")
# lr scheduler
# We cant decide on an actual number
NUM_WARMUP_STEPS = int(max_train_steps * 0.01)
accelerator.print(f"Num warmup steps: {NUM_WARMUP_STEPS}")
lr_scheduler = get_lr_scheduler_with_warmup(
optimizer=optim,
scheduler_type="cosine",
num_warmup_steps=NUM_WARMUP_STEPS,
max_train_steps=max_train_steps,
grad_accumulate_every=CFG.GRADIENT_ACCUMULATE_EVERY,
)
# prepare
model, optim, train_loader, lr_scheduler = accelerator.prepare(
model, optim, train_loader, lr_scheduler
)
# checkpoint scheduler
accelerator.register_for_checkpointing(lr_scheduler)
# I do not know why Huggingface recommends recalculation of max_train_steps
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps recalculated: {max_train_steps}")
# Total batch size for logging
total_batch_size = (
CFG.BATCH_SIZE * accelerator.num_processes * CFG.GRADIENT_ACCUMULATE_EVERY
)
accelerator.print(f"Total batch size: {total_batch_size}")
# resume training
progress_bar = tqdm(
range(max_train_steps), disable=not accelerator.is_local_main_process
)
completed_steps = 0
if CFG.RESUME_FROM_CHECKPOINT:
if CFG.RESUME_FROM_CHECKPOINT is not None or CFG.RESUME_FROM_CHECKPOINT != "":
accelerator.print(f"Resuming from checkpoint {CFG.RESUME_FROM_CHECKPOINT}")
accelerator.load_state(CFG.RESUME_FROM_CHECKPOINT)
path = os.path.basename(CFG.RESUME_FROM_CHECKPOINT)
training_difference = os.path.splitext(path)[0]
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = (
int(training_difference.replace("step_", ""))
* CFG.GRADIENT_ACCUMULATE_EVERY
)
if CFG.RESUME_FROM_CHECKPOINT and resume_step is not None:
train_loader = accelerator.skip_first_batches(train_loader, resume_step)
completed_steps += resume_step
progress_bar.update(resume_step)
# training
model.train()
for step, batch in enumerate(train_loader):
with accelerator.accumulate(model):
inputs = batch["input_ids"].to(accelerator.device)
loss = model(inputs, return_loss=True)
accelerator.backward(loss)
accelerator.log({"loss": loss.item()}, step=step)
if accelerator.sync_gradients:
accelerator.clip_grad_norm_(model.parameters(), 0.5)
optim.step()
lr_scheduler.step()
optim.zero_grad()
if accelerator.sync_gradients:
progress_bar.update(1)
completed_steps += 1
if isinstance(CFG.CHECKPOINTING_STEPS, int):
if completed_steps % CFG.CHECKPOINTING_STEPS == 0:
output_dir = f"step_{completed_steps }"
if CFG.OUTPUT_DIR is not None:
output_dir = os.path.join(CFG.OUTPUT_DIR, output_dir)
accelerator.save_state(output_dir)
if completed_steps >= max_train_steps:
break
# end training
# accelerator.print(f"Training Finished")
accelerator.end_training()
# save final model
# accelerator.print(f"Saving model to {CFG.OUTPUT_DIR}")
if CFG.OUTPUT_DIR is not None:
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
with accelerator.main_process_first():
accelerator.save(
unwrapped_model.state_dict(), f"{CFG.OUTPUT_DIR}/final/final_model.pt"
)
if __name__ == "__main__":
TrainKosmos() | Kosmos-X-master | old/training/train_kosmos.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
from accelerate import Accelerator
from accelerate.utils import InitProcessGroupKwargs
from datasets import concatenate_datasets, load_dataset
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
CheckpointImpl, apply_activation_checkpointing, checkpoint_wrapper)
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import (default_data_collator,
get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup, set_seed)
#sd
from lion_pytorch import Lion
# constants
# from .kosmos import Kosmos, KosmosTokenizer
from kosmosx.model import Kosmos, KosmosTokenizer
class CFG:
BATCH_SIZE: int = 3
GRADIENT_ACCUMULATE_EVERY: int = 1
SEED: int = 42
LEARNING_RATE: float = 1e-4
WEIGHT_DECAY: float = 1e-2
SEQ_LEN: int = 8192
NUM_CPU: int = multiprocessing.cpu_count()
USE_PRETOKENIZED: bool = True
USE_ACTIVATION_CHECKPOINTING: bool = True
RESUME_FROM_CHECKPOINT: str = None
CHECKPOINTING_STEPS: int = 1000
OUTPUT_DIR: str = "output"
ENTITY_NAME: str = "Kosmos"
# helpers
def print_num_params(model, accelerator: Accelerator):
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
accelerator.print(f"Number of parameters in model: {n_params}")
def fsdp_activation_checkpointing(
model, accelerator: Accelerator, offload_to_cpu=False
):
accelerator.print("Using FSDP activation checkpointing")
# check_fn = lambda submodule: isinstance(submodule, ParallelTransformerBlock)
non_reentrant_wrapper = partial(
checkpoint_wrapper,
offload_to_cpu=offload_to_cpu,
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
)
apply_activation_checkpointing(
model, checkpoint_wrapper_fn=non_reentrant_wrapper)
def get_lr_scheduler_with_warmup(
optimizer, scheduler_type, num_warmup_steps, max_train_steps, grad_accumulate_every
):
NUM_WARMUP_STEPS = num_warmup_steps
GRADIENT_ACCUMULATE_EVERY = grad_accumulate_every
if scheduler_type == "linear":
return get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
elif scheduler_type == "cosine":
return get_cosine_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
else:
raise ValueError(
"Invalid scheduler_type. Expected 'linear' or 'cosine', got: {}".format(
scheduler_type
)
)
# optimizers
def build_dataloaders():
tokenizer = KosmosTokenizer()
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train", streaming=True)
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
tokenized_dataset = dataset.map(
lambda example: tokenizer([t + tokenizer.eos_token for t in example["text"]]),
batched=True,
num_proc=CFG.NUM_CPU,
remove_columns=remove_columns,
)
block_size = CFG.SEQ_LEN
# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
# customize this part to your needs.
if total_length >= block_size:
total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated_examples.items()
}
return result
train_dataset = tokenized_dataset.map(
group_texts, batched=True, num_proc=CFG.NUM_CPU,
)
return train_dataset
# main
def TrainKosmos():
# accelerator
timeout = InitProcessGroupKwargs(timeout=timedelta(seconds=1_000_000))
accelerator = Accelerator(
gradient_accumulation_steps=CFG.GRADIENT_ACCUMULATE_EVERY,
mixed_precision="bf16",
log_with="wandb",
kwargs_handlers=[timeout],
)
accelerator.init_trackers(
project_name="Kosmos",
config={
"batch_size": CFG.BATCH_SIZE,
"gradient_accumulate_every": CFG.GRADIENT_ACCUMULATE_EVERY,
"learning_rate": CFG.LEARNING_RATE,
"seq_len": CFG.SEQ_LEN,
},
init_kwargs={"wandb": {"entity": CFG.ENTITY_NAME}},
)
accelerator.print(f"Total GPUS: {accelerator.num_processes}")
# set seed
set_seed(CFG.SEED)
# instantiate andromeda
model = Kosmos()
optim = Lion(model.parameters(), lr=1e-4, weight_decay=1e-2, use_triton=True)
print_num_params(model, accelerator)
if CFG.USE_ACTIVATION_CHECKPOINTING:
fsdp_activation_checkpointing(model, accelerator)
# dataloaders
if CFG.USE_PRETOKENIZED:
d0 = load_dataset("conceptofmind/c4_0-to-20_neox_with_eos_8k", split="train")
d1 = load_dataset("conceptofmind/c4_21-to-40_neox_with_eos_8k", split="train")
d2 = load_dataset("conceptofmind/c4_41-to-60_neox_with_eos_8k", split="train")
d3 = load_dataset("conceptofmind/c4_61-to-80_neox_with_eos_8k", split="train")
d4 = load_dataset("conceptofmind/c4_81-to-100_neox_with_eos_8k", split="train")
train_dataset = concatenate_datasets([d0, d1, d2, d3, d4])
else:
train_dataset = build_dataloaders()
train_loader = DataLoader(
train_dataset, batch_size=CFG.BATCH_SIZE, collate_fn=default_data_collator,
)
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps: {max_train_steps}")
# lr scheduler
# We cant decide on an actual number
NUM_WARMUP_STEPS = int(max_train_steps * 0.01)
accelerator.print(f"Num warmup steps: {NUM_WARMUP_STEPS}")
lr_scheduler = get_lr_scheduler_with_warmup(
optimizer=optim,
scheduler_type="cosine",
num_warmup_steps=NUM_WARMUP_STEPS,
max_train_steps=max_train_steps,
grad_accumulate_every=CFG.GRADIENT_ACCUMULATE_EVERY,
)
# prepare
model, optim, train_loader, lr_scheduler = accelerator.prepare(
model, optim, train_loader, lr_scheduler
)
# checkpoint scheduler
accelerator.register_for_checkpointing(lr_scheduler)
# I do not know why Huggingface recommends recalculation of max_train_steps
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps recalculated: {max_train_steps}")
# Total batch size for logging
total_batch_size = (
CFG.BATCH_SIZE * accelerator.num_processes * CFG.GRADIENT_ACCUMULATE_EVERY
)
accelerator.print(f"Total batch size: {total_batch_size}")
# resume training
progress_bar = tqdm(
range(max_train_steps), disable=not accelerator.is_local_main_process
)
completed_steps = 0
if CFG.RESUME_FROM_CHECKPOINT:
if CFG.RESUME_FROM_CHECKPOINT is not None or CFG.RESUME_FROM_CHECKPOINT != "":
accelerator.print(f"Resuming from checkpoint {CFG.RESUME_FROM_CHECKPOINT}")
accelerator.load_state(CFG.RESUME_FROM_CHECKPOINT)
path = os.path.basename(CFG.RESUME_FROM_CHECKPOINT)
training_difference = os.path.splitext(path)[0]
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = (
int(training_difference.replace("step_", ""))
* CFG.GRADIENT_ACCUMULATE_EVERY
)
if CFG.RESUME_FROM_CHECKPOINT and resume_step is not None:
train_loader = accelerator.skip_first_batches(train_loader, resume_step)
completed_steps += resume_step
progress_bar.update(resume_step)
# training
model.train()
for step, batch in enumerate(train_loader):
with accelerator.accumulate(model):
inputs = batch["input_ids"].to(accelerator.device)
loss = model(inputs, return_loss=True)
accelerator.backward(loss)
accelerator.log({"loss": loss.item()}, step=step)
if accelerator.sync_gradients:
accelerator.clip_grad_norm_(model.parameters(), 0.5)
optim.step()
lr_scheduler.step()
optim.zero_grad()
if accelerator.sync_gradients:
progress_bar.update(1)
completed_steps += 1
if isinstance(CFG.CHECKPOINTING_STEPS, int):
if completed_steps % CFG.CHECKPOINTING_STEPS == 0:
output_dir = f"step_{completed_steps }"
if CFG.OUTPUT_DIR is not None:
output_dir = os.path.join(CFG.OUTPUT_DIR, output_dir)
accelerator.save_state(output_dir)
if completed_steps >= max_train_steps:
break
# end training
# accelerator.print(f"Training Finished")
accelerator.end_training()
# save final model
# accelerator.print(f"Saving model to {CFG.OUTPUT_DIR}")
if CFG.OUTPUT_DIR is not None:
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
with accelerator.main_process_first():
accelerator.save(
unwrapped_model.state_dict(), f"{CFG.OUTPUT_DIR}/final/final_model.pt"
)
if __name__ == "__main__":
TrainKosmos() | Kosmos-X-master | old/training/training.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from kosmosx import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
from lion_pytorch import Lion
# to use Fullyshardeddataparalle
from torch.nn.parallel import DataParallel, DistributedDataParallel
import torch.distributed as dist
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
#optimizations
from apex import amp
from torch.cuda.amp import GradScaler
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
def prep_sample(sample):
question = sample["question"]
answer = sample["answer"].split("|!+")[1]
explanation = sample["explanation"]
text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
image = sample["image"]
return {
"image": image,
"target_text": text
}
def train(args):
if args.use_ddp:
dist.init_process_group(backend="nccl")
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
if args.use_ddp:
model = DistributedDataParallel(model)
else:
model = DataParallel(model)
model = model.to(accelerator.device)
#device count
if torch.cuda.device_count() > 1:
print(f"Let's use ${torch.cuda.device_count()} GPUS")
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
#wrap the model and optimizer with apex
model, optimizer = amp.initilize(model, optimizer, opt_level="01")
#gradient accumulation steps
#add gradient scaler for mixed precision training
GradScaler()
tokenizer = KosmosTokenizer()
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train[:30000]")
dataset = dataset.map(prep_sample, num_proc=8)
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=128, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[green]Training...", total=args.num_train_steps)
for step, batch in enumerate(train_dataloader):
batch_start = time.time()
optimizer.zero_grad()
# Forward pass
outputs = model(**batch)
loss = outputs.loss
# Backward pass
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
epoch_loss += loss.item()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
# Log metrics to Weights and Biases
wandb.log(logs, step=step)
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
# Log metrics to Accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
# Save the model weights to S3
save_model_to_s3(model, "kosmostraining", f"kosmosv1/checkpoints/checkpoint_at_step_{step}")
print(f"Saved to s3: checkpoint_at_step_{step}")
# Close TensorBoard writer
tb_writer.close()
# Finish Weights and Biases run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--use_ddp", action="store_true", help="Use DistributedDataParallel")
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/train_kosmos_optimized.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from .kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
from torch.nn.parallel import DataParallel, DistributedDataParallel
import torch.distributed as dist
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
def prep_sample(sample):
question = sample["question"]
answer = sample["answer"].split("|!+")[1]
explanation = sample["explanation"]
text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
image = sample["image"]
return {
"image": image,
"target_text": text
}
def train(args):
if args.use_ddp:
dist.init_process_group(backend="nccl")
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
if args.use_ddp:
model = DistributedDataParallel(model)
else:
model = DataParallel(model)
model = model.to(accelerator.device)
#device count
if torch.cuda.device_count() > 1:
print(f"Let's use ${torch.cuda.device_count()} GPUS")
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
#
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train[:40]")
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=128, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--use_ddp", action="store_true", help="Use DistributedDataParallel")
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/train_kosmos_original.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from .kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["answer"].split("|!+")[1]
# explanation = sample["explanation"]
# text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
# image = sample["image"]
# return {
# "image": image,
# "target_text": text
# }
def prep_sample(sample):
code = sample["code"]
language = sample["language"]
return {
"code": code,
"target_text": language
}
def train(args):
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
model = model.to(accelerator.device)
#V2 with FullyShardedData Parallel
# model = DistributedDataParallel(Kosmos())
# model = FullyShardedDataParallel(
# model(),
# fsdp_auto_wrap_policy=default_auto_wrap_policy,
# cpu_offload=CPUOffload(offload_params=True),
# )
#adam optimizer
# optimizer = AdamW8bit(model.parameters(), lr=args.learning_rate,
# weight_decay=args.weight_decay)
#LION
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3, beta1=0.9, beta=0.99)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
# dataset = load_dataset("bjoernp/vqax", split="test")
# #dataset = dataset.cast_column("URL", Image)
# dataset = dataset.map(prep_sample, num_proc=8)
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
dataset = load_dataset("codeparrot/github-code", streaming=True, split="train")
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
#old removed columns
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
#new removed columns
remove_columns = ['repo_name', 'path', 'language', 'license', 'size', 'code']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=512, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/training_kosmos_apex.py |
#quantization + paralleism
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from kosmosx import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
# to use Fullyshardeddataparalle
#from torch.distributed.dsdp import FullyShardedDataParalle, CPUOffload
#from torch.distributed.fsdp.wrap import default_auto_wrap_policy
from torch.nn.parallel import DataParallel, DistributedDataParallel
import torch.distributed as dist
# from torch.distributed.dsdp import (
# FullyShardedDataParallel,
# CPUOffload,
# )
# from torch.distributed.fsdp.wrap import (
# default_auto_wrap_policy,
# )
# from torch.nn.parallel import (
# DistributedDataParallel,
# )
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["answer"].split("|!+")[1]
# explanation = sample["explanation"]
# text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
# image = sample["image"]
# return {
# "image": image,
# "target_text": text
# }
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["multiple_choice_answer"]
# # You may need to preprocess the image according to your model's requirements
# image = sample["image"]
# text = f"Question: {question} Answer: {answer}"
# return {
# "image": image,
# "target_text": text
# }
def prep_sample(sample):
question = sample["question"]
answer = sample["answer"].split("|!+")[1]
explanation = sample["explanation"]
text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
image = sample["image"]
return {
"image": image,
"target_text": text
}
def train(args):
if args.use_ddp:
dist.init_process_group(backend="nccl")
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
if args.use_ddp:
model = DistributedDataParallel(model)
else:
model = DataParallel(model)
model = model.to(accelerator.device)
#device count
if torch.cuda.device_count() > 1:
print(f"Let's use ${torch.cuda.device_count()} GPUS")
# model = model.to(accelerator.device)
#V2 with FullyShardedData Parallel
# model = DistributedDataParallel(Kosmos())
# model = FullyShardedDataParallel(
# model(),
# fsdp_auto_wrap_policy=default_auto_wrap_policy,
# cpu_offload=CPUOffload(offload_params=True),
# )
#v3
# model = Kosmos()
# model = FullyShardedDataParallel(
# model,
# fsdp_auto_wrap_policy=default_auto_wrap_policy,
# cpu_offload=CPUOffload(offload_params=True),
# )
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
# dataset = load_dataset("bjoernp/vqax", split="test")
# #dataset = dataset.cast_column("URL", Image)
# dataset = dataset.map(prep_sample, num_proc=8)
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
dataset = load_dataset("HuggingFaceM4/VQAv2", split="train[:30000]")
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
#old removed columns
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
#new removed columns
remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=128, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
# dataset = load_dataset("bjoernp/vqax", split="test")
# #dataset = dataset.cast_column("URL", Image)
# dataset = dataset.map(prep_sample, num_proc=8)
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
# dataset = dataset.map(tokenizer.tokenize, batched=True,
# batch_size=128, remove_columns=remove_columns)
# train_dataloader = DataLoader(
# dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
# )
# model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
# lr_scheduler)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--use_ddp", action="store_true", help="Use DistributedDataParallel")
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/training_kosmos_3.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from .kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
# from torch.distributed.dsdp import (
# FullyShardedDataParallel,
# CPUOffload,
# )
# from torch.distributed.fsdp.wrap import (
# default_auto_wrap_policy,
# )
# from torch.nn.parallel import (
# DistributedDataParallel,
# )
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["answer"].split("|!+")[1]
# explanation = sample["explanation"]
# text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
# image = sample["image"]
# return {
# "image": image,
# "target_text": text
# }
def prep_sample(sample):
code = sample["code"]
language = sample["language"]
return {
"code": code,
"target_text": language
}
def train(args):
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
model = model.to(accelerator.device)
#V2 with FullyShardedData Parallel
# model = DistributedDataParallel(Kosmos())
# model = FullyShardedDataParallel(
# model(),
# fsdp_auto_wrap_policy=default_auto_wrap_policy,
# cpu_offload=CPUOffload(offload_params=True),
# )
#adam optimizer
# optimizer = AdamW8bit(model.parameters(), lr=args.learning_rate,
# weight_decay=args.weight_decay)
#LION
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3, beta1=0.9, beta=0.99)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
# dataset = load_dataset("bjoernp/vqax", split="test")
# #dataset = dataset.cast_column("URL", Image)
# dataset = dataset.map(prep_sample, num_proc=8)
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
dataset = load_dataset("codeparrot/github-code", streaming=True, split="train")
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
#old removed columns
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
#new removed columns
remove_columns = ['repo_name', 'path', 'language', 'license', 'size', 'code']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=512, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/train_kosmos_text.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from .kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
# from torch.distributed.dsdp import (
# FullyShardedDataParallel,
# CPUOffload,
# )
# from torch.distributed.fsdp.wrap import (
# default_auto_wrap_policy,
# )
# from torch.nn.parallel import (
# DistributedDataParallel,
# )
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["answer"].split("|!+")[1]
# explanation = sample["explanation"]
# text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
# image = sample["image"]
# return {
# "image": image,
# "target_text": text
# }
def prep_sample(sample):
code = sample["code"]
language = sample["language"]
return {
"code": code,
"target_text": language
}
def train(args):
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
model = model.to(accelerator.device)
#V2 with FullyShardedData Parallel
# model = DistributedDataParallel(Kosmos())
# model = FullyShardedDataParallel(
# model(),
# fsdp_auto_wrap_policy=default_auto_wrap_policy,
# cpu_offload=CPUOffload(offload_params=True),
# )
#adam optimizer
# optimizer = AdamW8bit(model.parameters(), lr=args.learning_rate,
# weight_decay=args.weight_decay)
#LION
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3, beta1=0.9, beta=0.99)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
# dataset = load_dataset("bjoernp/vqax", split="test")
# #dataset = dataset.cast_column("URL", Image)
# dataset = dataset.map(prep_sample, num_proc=8)
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
dataset = load_dataset("codeparrot/github-code", streaming=True, split="train")
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
#old removed columns
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
#new removed columns
remove_columns = ['repo_name', 'path', 'language', 'license', 'size', 'code']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=512, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/train_kosmos_code.py |
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from .kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
# from torch.distributed.dsdp import (
# FullyShardedDataParallel,
# CPUOffload,
# )
# from torch.distributed.fsdp.wrap import (
# default_auto_wrap_policy,
# )
# from torch.nn.parallel import (
# DistributedDataParallel,
# )
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["answer"].split("|!+")[1]
# explanation = sample["explanation"]
# text = f"Question: {question} Answer: {answer} Explanation: {explanation}"
# image = sample["image"]
# return {
# "image": image,
# "target_text": text
# }
# def prep_sample(sample):
# question = sample["question"]
# answer = sample["multiple_choice_answer"]
# # You may need to preprocess the image according to your model's requirements
# image = sample["image"]
# text = f"Question: {question} Answer: {answer}"
# return {
# "image": image,
# "target_text": text
# }
def prep_sample(sample):
question = sample["question"]
answer = sample["choices"][sample["answer"]]
image = sample["image"]
text = f"Question: {question} Answer: {answer}"
return {
"image": image,
"target_text": text
}
def train(args):
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
model = model.to(accelerator.device)
#V2 with FullyShardedData Parallel
# model = DistributedDataParallel(Kosmos())
# model = FullyShardedDataParallel(
# model(),
# fsdp_auto_wrap_policy=default_auto_wrap_policy,
# cpu_offload=CPUOffload(offload_params=True),
# )
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer()
#====================> load data #====================> load data #====================> load data
# dataset = load_dataset("bjoernp/vqax", split="test")
# #dataset = dataset.cast_column("URL", Image)
# dataset = dataset.map(prep_sample, num_proc=8)
# remove_columns = ['id', 'img_id', 'question', 'answer',
# 'explanation', 'none', 'image', 'target_text']
# dataset = load_dataset("HuggingFaceM4/VQAv2")
# # dataset = dataset.map(prep_sample, num_proc=8)
# dataset = dataset.map(prep_sample, num_proc=8)
# #old removed columns
# # remove_columns = ['id', 'img_id', 'question', 'answer',
# # 'explanation', 'none', 'image', 'target_text']
# #new removed columns
# remove_columns = ['question_type', 'multiple_choice_answer', 'answers', 'image_id', 'answer_type', 'question_id', 'question', 'image']
# dataset = dataset.map(tokenizer.tokenize, batched=True,
# batch_size=128, remove_columns=remove_columns)
# train_dataloader = DataLoader(
# dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
# )
dataset = load_dataset("derek-thomas/ScienceQA")
dataset = dataset.map(prep_sample, num_proc=8)
remove_columns = ['image', 'question', 'choices', 'answer', 'hint', 'task', 'grade', 'subject', 'topic', 'category', 'skill', 'lecture', 'solution']
dataset = dataset.map(tokenizer.tokenize, batched=True,
batch_size=128, remove_columns=remove_columns)
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = next(train_loader)
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--max_steps", type=int, default=100000)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--log_every", type=int, default=1)
parser.add_argument("--save_every", type=int, default=100)
parser.add_argument("--seed", type=int, default=None)
args = parser.parse_args()
train(args)
| Kosmos-X-master | old/training/experiments/train_kosmos.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from transformers import Wav2Vec2Tokenizer
from transformers import Wav2Vec2Model
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self, modalities=["text", "image", "audio"]):
self.modalities = modalities
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
# T5 uses SentencePiece tokenizer
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>"],
extra_ids=0,
model_max_length=1984
)
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.audio_tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h")
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_ids
def tokenize(self, target_texts):
text_tokens_list, only_text_tokens_list = [], []
max_length = 0
for target_text in target_texts:
text_tokens, only_text_tokens = self.tokenize_texts(target_text)
text_tokens_list.append(text_tokens)
only_text_tokens_list.append(only_text_tokens)
max_length = max(max_length, text_tokens.shape[1])
padded_text_tokens_list = []
padded_only_text_tokens_list = []
for text_tokens, only_text_tokens in zip(text_tokens_list, only_text_tokens_list):
padded_text_tokens = torch.cat([text_tokens, torch.full((1, max_length - text_tokens.shape[1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=1)
padded_only_text_tokens = torch.cat([only_text_tokens, torch.full((1, max_length - only_text_tokens.shape[1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=1)
padded_text_tokens_list.append(padded_text_tokens)
padded_only_text_tokens_list.append(padded_only_text_tokens)
attention_mask = torch.stack(padded_text_tokens_list) != self.tokenizer.pad_token_id
return {
"text_tokens": torch.stack(padded_text_tokens_list),
"labels": torch.stack(padded_only_text_tokens_list),
"attention_mask": attention_mask,
}
class Kosmos(Module):
def __init__(self, modalities=["text", "image", "audio"]):
super().__init__()
# Instantiate Clip Vit-l/14
self.modalities = modalities
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.audio_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
#add audio
self.audio_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images=None, audios=None, **kwargs):
if "image" in self.modalities and images is not None:
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
if "audio" in self.modalities and audios is not None:
audios = self.audio_model(input_ids=audios).last_hidden_state
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
model_input = self.decoder.forward_embedding(text_tokens)[1]
if "image" in self.modalities and images is not None and "audio" in self.modalities and audios is not None:
model_input = torch.cat([model_input[:, 0:3], images, audios, model_input[:, 3:]], dim=1)
elif "image" in self.modalities and images is not None:
model_input = torch.cat([model_input[:, 0:3], images, model_input[:, 3:]], dim=1)
elif "audio" in self.modalities and audios is not None:
model_input = torch.cat([model_input[:, 0:3], audios, model_input[:, 3:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0]
import time
import torch
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
# from kosmos import Kosmos, KosmosTokenizer
from accelerate import Accelerator
from rich.progress import Progress
from lion_pytorch import Lion
import torch.distributed as dist
AWS_ACCESS_KEY_ID= 'AKIA5K4H36GT5EVDX2MA'
AWS_SECRET_ACCESS_KEY= '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'
WANDB_API_KEY= '0fc08bb0e90314a2bb602afa0b2e6cf56abc3f49'
#logging
import boto3
#training
import wandb
from torch.utils.tensorboard import SummaryWriter
def save_model_to_s3(model, bucket_name, key_prefix, step):
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
model_path = f"checkpoint_at_step_{step}.pt"
torch.save(model.state_dict(), model_path)
s3.upload_file(model_path, bucket_name, f"{key_prefix}/{model_path}")
def count_number_of_parameters(model, only_trainable: bool = True) -> int:
if only_trainable:
num_params: int = sum(p.numel()
for p in model.parameters() if p.requires_grad)
else:
num_params: int = sum(p.numel() for p in model.parameters() if p)
return int(num_params)
# def load_alpaca_cot_dataset(data_dir: str) -> DatasetDict:
# data_dir = Path(data_dir)
# dataset = {"train": [], "validation": []}
# for split in dataset.keys():
# for file in (data_dir / split).glob("*json"):
# with open(file, "r") as f:
# data = json.load(f)
# dataset[split].extend(data)
# return DatasetDict({split: Dataset.from_dict({"data": data}) for split, data in dataset.items()})
def prep_sample(sample):
instruction = sample["instruction"]
input_text = sample["input"]
output_text = sample["output"]
text = f"Instruction: {instruction} Input: {input_text} Output: {output_text}"
return {
"target_text": text
}
def train(args):
if args.use_ddp:
dist.init_process_group(backend="nccl")
accelerator = Accelerator(
mixed_precision="fp16"
)
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
#v1
model = Kosmos()
# if args.use_ddp:
# model = DistributedDataParallel(model)
# else:
# model = DataParallel(model)
model = model.to(accelerator.device)
#device count
if torch.cuda.device_count() > 1:
print(f"Let's use ${torch.cuda.device_count()} GPUS")
optimizer = Lion(model.parameters(), lr=args.learning_rate / 3, weight_decay=args.weight_decay * 3)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=args.warmup_steps,
num_training_steps=args.max_steps,
)
tokenizer = KosmosTokenizer(modalities=["text"])
# dataset = load_dataset("QingyiSi/Alpaca-CoT", split="train[:1%]")
# dataset = load_dataset("yahma/alpaca-cleaned", split="train[:1%]")
dataset = load_dataset("yahma/alpaca-cleaned", split="train")
# dataset = dataset.map(prep_sample, num_proc=8)
dataset = dataset.map(prep_sample, num_proc=8)
# dataset = dataset.map(lambda sample: tokenizer(sample["target_text"]), batched=True, batch_size=128, remove_columns=["instruction", "input", "output"])
dataset = dataset.map(lambda sample: (print(sample), tokenizer.tokenize(sample))[1], batched=True, batch_size=128, remove_columns=["instruction", "input", "output"], input_columns=["target_text"])
train_dataloader = DataLoader(
dataset, collate_fn=default_data_collator, batch_size=args.batch_size, pin_memory=True
)
#====================> load data #====================> load data #====================> load data #====================> load data
model, train_dataloader, optimizer, lr_scheduler = accelerator.prepare(model, train_dataloader, optimizer,
lr_scheduler)
model.train()
accelerator.register_for_checkpointing(lr_scheduler)
model.clip_model.requires_grad_(False)
model.clip_model.encoder.layers[-1].requires_grad_(True)
accelerator.print(
f"Number of parameters: {count_number_of_parameters(model):,}")
accelerator.print(
f"Number of trainable parameters: {count_number_of_parameters(model, only_trainable=True):,}")
# Log model and optimizer parameters to wandb
accelerator.init_trackers(project_name="kosmos")
#wandb
wandb.init(project="kosmos", config=args)
#init tensorboard writer
tb_writer = SummaryWriter()
train_loader = iter(train_dataloader)
epoch_loss = 0
total_loss = 0
start_time = time.time()
with Progress() as progress:
task = progress.add_task("[red]Training...", total=args.max_steps)
for step in range(0, args.max_steps):
batch_start = time.time()
batch = {key: value for key, value in next(train_loader).items() if key != "images"}
outputs = model(**batch, self_attn_padding_mask=batch["attention_mask"])
# Shift so that tokens < n predict n
outputs = torch.cat([outputs[:, :1], outputs[:, 67:]], dim=1).contiguous()
# shift_logits = outputs[..., :-1, :].contiguous()
# shift_labels = batch["labels"][..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
one_hot_labels = torch.nn.functional.one_hot(batch["labels"][:, 1:], num_classes=32002).float()
loss = loss_fct(outputs[:,:-1], one_hot_labels)
epoch_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
batch_end = time.time()
logs = {
"loss": loss.item(),
"perplexity": torch.exp(loss).item(),
"lr": lr_scheduler.get_last_lr()[0],
"examples": args.batch_size * (step + 1),
"examples_per_second": args.batch_size / (batch_end - batch_start),
}
if step % args.log_every == args.log_every - 1:
#log metrics to wandb
wandb.log(logs, step=step)
#log metrics to tensorboard
# Log metrics to TensorBoard
tb_writer.add_scalar("loss", logs["loss"], step)
tb_writer.add_scalar("perplexity", logs["perplexity"], step)
tb_writer.add_scalar("lr", logs["lr"], step)
tb_writer.add_scalar("examples", logs["examples"], step)
tb_writer.add_scalar("examples_per_second", logs["examples_per_second"], step)
#accelerator
accelerator.log(logs, step=step)
progress.update(task, advance=1, description=f"Step Loss: {loss.item():.5f} "
f"| Mean Loss: {(total_loss + epoch_loss) / step:.5f} "
f"| Mean PPL: {torch.exp((total_loss + epoch_loss) / step):.2f} "
f"| Examples: {args.batch_size * (step + 1)} "
f"| Examples/s: {args.batch_size / (batch_end - batch_start):.2f} "
f"| Elapsed: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
if step % args.save_every == args.save_every - 1:
train_epoch_loss = epoch_loss / args.save_every
total_loss += epoch_loss
epoch_loss = 0
accelerator.log({
"train_ppl": torch.exp(train_epoch_loss),
"train_epoch_loss": train_epoch_loss,
}, step=step)
progress.print(f"Saving checkpoint at step {step}...")
accelerator.save_state(
f"{args.checkpoint_dir}/checkpoint_at_step_{step}/")
#save the model weights to s3
save_model_to_s3(model, "kosmostraining", "kosmosv1/checkpoints", step)
print(f"Saved to s3: {save_model_to_s3} ")
#finish tensorboard writer
tb_writer.close()
#finish wnabd run
wandb.finish()
class Args:
def __init__(self):
self.checkpoint_dir = "checkpoints"
self.learning_rate = 1e-5
self.weight_decay = 0.01
self.warmup_steps = 0
self.max_steps = 100000
self.batch_size = 4
self.log_every = 1
self.save_every = 100
self.seed = None
self.use_ddp = False
args = Args()
train(args) | Kosmos-X-master | old/training/notebookExperiments/main.py |
from kosmosx.model import KosmosTokenizer, Kosmos
from kosmosx.tokenize import BuildDataset | Kosmos-X-master | kosmosx/__init__.py |
import logging
import torch
import torch.nn as nn
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
from transformers import AutoTokenizer, CLIPModel, CLIPProcessor
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Check if the modules are available
try:
import bitsandbytes
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
except ImportError as e:
logging.error(f"Failed to import module: {e}")
raise
class KosmosTokenizer:
"""
A tokenizer class for the kosmos model
Attributes:
processor(CLIPProcessor): The processor to tokenize images
tokenizer: (AutoTokenizer): The tokenizer to tokenize text
im_idx: (int): The Index of the "<image>" token.
im_end_idx (int): The index of the "</image>" token.
"""
def __init__(self):
try:
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
self.tokenizer = AutoTokenizer.from_pretrained(
"EleutherAI/gpt-neox-20b",
additional_special_tokens=["<image>", "</image>"],
eos_token="<eos>",
pad_token="<pad>",
extra_ids=0,
model_max_length=8192
)
except Exception as e:
logging.error(f"Failed to initialize KosmosTokenizer: {e}")
raise
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
def tokenize_texts(self, texts: str):
"""
Tokenize given texts.
Args:
Texts (str): The Text to be tokenized
Returns:
A tuple containing the tokenized texts and only the text tokens.
"""
try:
texts = self.tokenizer(
texts,
return_tensors="pt",
padding=True,
truncation=True
).input_ids
# Add image tokens to text as "<s> <image> </image> text </s>"
image_tokens = torch.tensor([[self.im_idx, self.im_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], image_tokens, texts[:, 1:]], dim=1), texts
except Exception as e:
logging.error(f"Failed to tokenize texts: {e}")
raise
def tokenize_images(self, images):
"""
Tokenizes given images.
Args:
images: The images to be tokenized
Returns:
The tokenized images.
"""
try:
return self.processor(images=images, return_tensors="pt").pixel_values
except Exception as e:
logging.error(f"Failed to tokenize images: {e}")
raise
def tokenize(self, sample):
"""
Tokenizes given sample.
Args:
Sample: The sample to be tokenized
Returns:
A dictionary containing the tokenized text tokens, images, labels, and attention mask.
"""
try:
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
}
except Exception as e:
logging.error(f"Failed to tokenize sample: {e}")
raise
class Kosmos(nn.Module):
"""
The main Kosmos model class.
Attributes:
clip_model (CLIPModel): The CLIP model for image processing.
embed (Embedding): The embedding layer for tokens.
embed_positions: (PositionEmbedding): The positional embedding layer.
output_projection (Linear): the output projection layer.
config (DecoderConfig): The configuration for the decoder
decoder (Decoder): The decoder module
perceieve(PerceiverResampler): The PerceieverResampler module for image processing.
image_proj (Linear): The image projection layer.
"""
def __init__(self):
super().__init__()
# Instantiate Clip Vit-l/14
try:
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
except Exception as e:
logging.error(f"Failed to initialize CLIP model: {e}")
raise
self.embed = bitsandbytes.nn.modules.Embedding(32002, 2048, padding_idx=1)
self.embed_positions= PositionalEmbedding(2048, 2048, 1)
self.output_projection = nn.Linear(2048, 32002, bias=False)
nn.init.normal_(self.output_projection.weight, mean=0, std=2048**-0.5)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
multiway=True,
max_rel_pos=2048,
)
try:
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
except Exception as e:
logging.error(f"Failed to initialize Decoder: {e}")
raise
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = nn.Linear(1024, 2048, bias=False)
nn.init.normal_(self.image_proj.weight, mean=0, std=2048**-0.5)
def forward(
self,
text_tokens: torch.Tensor,
images: torch.Tensor,
**kwargs
):
"""
The forward pass for the Kosmos model.
Args:
text_tokens (torch.Tensor): The text tokens.
images (torch.Tensor): The image tokens.
Returns:
The output of the decoder
"""
if not isinstance(text_tokens, torch.Tensor) or not isinstance(images, torch.Tensor):
raise TypeError("text_tokens and images must be instances of torch.Tensor")
try:
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
except Exception as e:
logging.error(f"Failed during image processing: {e}")
raise
try:
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:2], images, model_input[:, 2:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
except Exception as e:
logging.error(f"Failed during text processing: {e}")
raise
try:
return self.decoder(model_input, passed_x=model_input)[0]
except Exception as e:
logging.error(f"Failed during model forward pass: {e}")
raise
class KosmosLanguage(Module):
def __init__(self):
super().__init__()
self.embed = bitsandbytes.nn.modules.Embedding(
320002,
2048,
padding_idx=1
)
self.embed_positions = PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
multiway=True,
max_rel_pos=2048,
alibi_pos_bias=True,
alibi_num_heads=16,
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
def forward(
self,
text_tokens,
**kwargs
):
model_input = self.decoder.forward_embedding(text_tokens)[0]
return self.decoder(model_input, passed_x=model_input)[0]
| Kosmos-X-master | kosmosx/model.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
import torch
########### SETUP CONFIG
import torch.distributed as dist
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.state import AcceleratorState
from accelerate.utils import DummyOptim, InitProcessGroupKwargs
from datasets import load_dataset
from lion_pytorch import Lion
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
CheckpointImpl,
apply_activation_checkpointing,
checkpoint_wrapper,
)
# import bitsandbytes as bnb
from torch.distributed.fsdp import (
BackwardPrefetch,
FullyShardedDataParallel,
MixedPrecision,
ShardingStrategy,
)
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
from torch.nn import LayerNorm
from torch.optim import AdamW
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import (
AutoTokenizer,
default_data_collator,
get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup,
set_seed,
)
from kosmosx.model import Decoder, Kosmos
from kosmosx.utils.stable_adamw import StableAdamWUnfused
# state = AcceleratorState()
logger = get_logger(__name__, log_level="INFO")
class CFG:
BATCH_SIZE = 1
GRADIENT_ACCUMULATE_EVERY: int = 1
SEED: int = 42
LEARNING_RATE: float = 1e-4 #3e-4 # 1e-4 for lion
WEIGHT_DECAY: float = 0.1
SEQ_LEN: int = 8192
NUM_CPU: int = multiprocessing.cpu_count()
USE_DEEPSPEED: bool = True
USE_FSDP: bool = True
USE_PRETOKENIZED: bool = True
USE_ACTIVATION_CHECKPOINTING: bool = True
RESUME_FROM_CHECKPOINT: str = False
CHECKPOINTING_STEPS: int = 1000
OUTPUT_DIR: str = 'checkpoints/' # Folder
ENTITY_NAME: str = "Kosmos"
LOGGING_STEPS: int = 100
# helpers
def print_num_params(model, accelerator: Accelerator):
# n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
accelerator.print(f"Number of parameters in model: {n_params}")
# activation checkpointing
def activation_checkpointing(
model: torch.nn.Module,
offload_to_cpu: bool = False,
accelerator: Accelerator = None,
):
"""
Apply activation checkpointing to a model.
Args:
model (Module): The model to which to apply activation checkpointing.
offload_to_cpu (bool, optional): Whether to offload the activations to CPU. Defaults to False.
accelerator (Accelerator, optional): The Accelerate library accelerator. Defaults to None.
"""
if accelerator is not None:
accelerator.print("Using activation checkpointing")
def check_fn(submodule):
return isinstance(submodule, Decoder)
non_reentrant_wrapper = partial(
checkpoint_wrapper,
offload_to_cpu=offload_to_cpu,
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
)
apply_activation_checkpointing(
model, checkpoint_wrapper_fn=non_reentrant_wrapper, check_fn=check_fn
)
# FSDP
def fsdp(
model: torch.nn.Module,
auto_wrap: bool = False,
mp: str = "fp32",
shard_strat: str = "NO_SHARD",
):
"""
This function wraps a given PyTorch model with the FullyShardedDataParallel (FSDP) wrapper to enable efficient data parallelism and model sharding.
Args:
model (torch.nn.Module): The original PyTorch model to be wrapped with FSDP.
auto_wrap (bool, optional): If True, it enables automatic wrapping of the model's layers according to the transformer_auto_wrap_policy. Default is False.
mp (str, optional): The mixed precision mode to be used. Can be 'bf16' for BFloat16, 'fp16' for Float16 or 'fp32' for Float32 precision. Default is 'fp32'.
shard_strat (str, optional): The sharding strategy to be used. Can be 'SHARD_GRAD' for sharding at gradient computation, 'FULL_SHARD' for full model sharding or 'NO_SHARD' for no sharding. Default is 'NO_SHARD'.
Raises:
ValueError: If the provided mp (mixed precision mode) is not 'bf16', 'fp16' or 'fp32'.
ValueError: If the provided shard_strat (sharding strategy) is not 'SHARD_GRAD', 'FULL_SHARD' or 'NO_SHARD'.
Returns:
torch.nn.Module: The input model wrapped with FSDP.
"""
if auto_wrap:
Kosmos_auto_wrap_policy = partial(
transformer_auto_wrap_policy,
transformer_layer_cls={
Decoder,
},
)
else:
Kosmos_auto_wrap_policy = None
if mp == "bf16":
mp_fsdp = MixedPrecision(
param_dtype=torch.bfloat16,
# Gradient communication precision.
reduce_dtype=torch.bfloat16,
# Buffer precision.
buffer_dtype=torch.bfloat16,
)
elif mp == "fp16":
mp_fsdp = MixedPrecision(
param_dtype=torch.float16,
# Gradient communication precision.
reduce_dtype=torch.float16,
# Buffer precision.
buffer_dtype=torch.float16,
)
elif mp == "fp32":
mp_fsdp = MixedPrecision(
param_dtype=torch.float32,
# Gradient communication precision.
reduce_dtype=torch.float32,
# Buffer precision.
buffer_dtype=torch.float32,
)
else:
raise ValueError(
"Invalid scheduler_type. Expected 'bf16', 'fp16' or 'fp32', got: {}".format(
mp
)
)
if shard_strat == "SHARD_GRAD":
sharding_strat_fsdp = ShardingStrategy.SHARD_GRAD_OP
elif shard_strat == "FULL_SHARD":
sharding_strat_fsdp = ShardingStrategy.FULL_SHARD
elif shard_strat == "NO_SHARD":
sharding_strat_fsdp = ShardingStrategy.NO_SHARD
else:
raise ValueError(
"Invalid scheduler_type. Expected 'SHARD_GRAD', 'FULL_SHARD' or 'NO_SHARD', got: {}".format(
shard_strat
)
)
model = FullyShardedDataParallel(
model,
auto_wrap_policy=Kosmos_auto_wrap_policy,
mixed_precision=mp_fsdp,
backward_prefetch=BackwardPrefetch.BACKWARD_PRE,
sharding_strategy=sharding_strat_fsdp,
forward_prefetch=True,
use_orig_params=True,
)
return model
# learning rate scheduler
def get_lr_scheduler_with_warmup(
optimizer: torch.optim.Optimizer,
scheduler_type: str,
num_warmup_steps: int,
max_train_steps: int,
grad_accumulate_every: int = 1,
accelerator: Accelerator = None,
):
"""
Get a learning rate scheduler with warmup.
Args:
optimizer (Optimizer): The optimizer for which to create the learning rate scheduler.
scheduler_type (str): The type of learning rate scheduler to create, either "linear" or "cosine".
num_warmup_steps (int): The number of warmup steps for the learning rate scheduler.
max_train_steps (int): The maximum number of training steps.
grad_accumulate_every (int, optional): The gradient accumulation factor. Defaults to 1.
accelerator (Accelerator, optional): The Accelerate library accelerator. Defaults to None.
Returns:
The learning rate scheduler with warmup.
Raises:
ValueError: If scheduler_type is not "linear" or "cosine".
"""
NUM_WARMUP_STEPS = num_warmup_steps
GRADIENT_ACCUMULATE_EVERY = grad_accumulate_every
if accelerator is not None:
accelerator.print(f"Using {scheduler_type} lr scheduler")
if scheduler_type == "linear":
return get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
elif scheduler_type == "cosine":
return get_cosine_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=NUM_WARMUP_STEPS * GRADIENT_ACCUMULATE_EVERY,
num_training_steps=max_train_steps * GRADIENT_ACCUMULATE_EVERY,
)
else:
raise ValueError(
"Invalid scheduler_type. Expected 'linear' or 'cosine', got: {}".format(
scheduler_type
)
)
# optimizers
def decoupled_optimizer(
model: torch.nn.Module,
learning_rate: float,
weight_decay: float,
beta_1: float,
beta_2: float,
optimizer_type: str,
use_fsdp: bool = True,
accelerator: Accelerator = None,
):
"""
Decouples the optimizer from the training process.
This function sets up the optimizer for the model by creating two groups of parameters:
one for weight decay and one without weight decay. Then, it initializes the optimizer
with these two groups of parameters.
Args:
model (Module): The model whose parameters are optimized.
learning_rate (float): The learning rate for the optimizer.
weight_decay (float): The weight decay for the optimizer.
beta_1 (float): The exponential decay rate for the 1st moment estimates.
beta_2 (float): The exponential decay rate for the 2nd moment estimates.
optimizer_type (str): The type of the optimizer. Can be 'lion', 'adamw', or 'stable_adamw'.
use_fsdp (bool, optional): If True, the optimizer will work with fully sharded data parallelism. Defaults to True.
accelerator (Accelerator, optional): The accelerator from HuggingFace's Accelerate library. Defaults to None.
Returns:
Optimizer: The initialized optimizer.
Raises:
ValueError: If the optimizer type is not 'lion', 'adamw' or 'stable_adamw'.
"""
accelerator.print(f"Using {optimizer_type} optimizer")
# Create an empty dictionary called param_dict to store the model's named parameters.
param_dict = {}
# Iterate over the model's named parameters and populate the param_dict with key-value pairs.
for param_name, param in model.named_parameters():
param_dict[param_name] = param
# Separate the model's named modules into two groups: decay and no_decay.
# Create an empty list to store the names of the LayerNorm and Embedding layer weights with no weight decay.
no_decay = []
if use_fsdp:
exclude_module = "_fsdp_wrapped_module.token_emb"
else:
exclude_module = "token_emb"
# Iterate through the named modules of the model.
for module_name, module in model.named_modules():
# Check if the current module is an instance of any of the desired types (LayerNorm or torch.nn.Embedding).
for ndim in [LayerNorm, torch.nn.Embedding]:
if isinstance(module, ndim):
# If torch.nn.Embedding, append its name with a ".weight" suffix to the no_decay list.
if module_name == exclude_module:
no_decay.append(f"{module_name}.weight")
else:
# If the module is an instance of LayerNorm
no_decay.append(f"{module_name}.gamma")
# Exit the inner loop since the desired module has been found.
break
# Create an empty list to store the names of the Linear layer weights with weight decay.
decay = []
# Iterate through the named modules of the model.
for module_name, module in model.named_modules():
# Check if the current module is an instance of the desired type (torch.nn.Linear).
for ndim in [torch.nn.Linear]:
if isinstance(module, ndim):
# If the module is an instance of torch.nn.Linear, append its name with a ".weight" suffix to the decay list.
decay.append(f"{module_name}.weight")
# Exit the inner loop since the desired module has been found.
break
# Create two separate lists of model parameters: decay_param and no_decay_param.
# The decay_param list contains the parameters that should have weight decay applied.
# The no_decay_param list contains the parameters that should not have weight decay applied, excluding the 'to_logits.weight' parameter.
# Create an empty list called decay_param to store the parameters with weight decay.
decay_param = []
if use_fsdp:
exclude_param = "_fsdp_wrapped_module.to_logits.weight"
else:
exclude_param = "to_logits.weight"
# Iterate over the decay list, which contains the names of the parameters with weight decay.
for param in decay:
# Check if the current parameter is not 'to_logits.weight'.
# Append the corresponding parameter from param_dict to the decay_param list.
if param != exclude_param:
decay_param.append(param_dict[param])
# Create an empty list called no_decay_param to store the parameters without weight decay.
no_decay_param = []
# Iterate over the no_decay list, which contains the names of the parameters without weight decay.
for param in no_decay:
try:
# Append the corresponding parameter from param_dict to the no_decay_param list.
no_decay_param.append(param_dict[param])
except KeyError:
# print(f"Parameter {param_name} does not exist in the model")
pass
# Create a list called grouped_params that contains two dictionaries.
# The first dictionary has the decay_param list and the corresponding weight_decay value.
# The second dictionary has the no_decay_param list and a weight_decay value of 0.0.
grouped_params = [
{"params": decay_param, "weight_decay": weight_decay},
{"params": no_decay_param, "weight_decay": 0.0},
]
# Create a variable called optimizer that stores an instance of the optimizer.
if optimizer_type == "lion":
optimizer = Lion(grouped_params, lr=learning_rate, betas=(beta_1, beta_2),)
elif optimizer_type == "adamw":
optimizer = AdamW(grouped_params, lr=learning_rate, betas=(beta_1, beta_2),)
elif optimizer_type == "deepspeed":
optimizer = DummyOptim(grouped_params, lr=learning_rate, betas=(beta_1, beta_2),)
elif optimizer_type == "stable_adamw":
optimizer = StableAdamWUnfused(
grouped_params, lr=learning_rate, betas=(beta_1, beta_2),
)
# elif optimizer_type=="Adam8bit":
# optimizer = bnb.optim.Adam8bit(grouped_params, lr=learning_rate, betas=(beta_1, beta_2))
# elif optimizer_type=="Lion8Bit":
# optimizer = bnb.optim.Lion8bit(grouped_params, lr=learning_rate, betas=(beta_1, beta_2))
else:
raise ValueError(
"Invalid optimizer_type. Expected 'lion', 'adamw', 'deepspeed' or 'stable_adamw', got: {}".format(
optimizer_type
)
)
# Return the optimizer.
return optimizer
# dataloaders
def build_dataloaders():
"""
Build data loaders for training.
This function performs the following steps:
1. Load the tokenizer from the pretrained "EleutherAI/gpt-neox-20b" model.
2. Load the "openwebtext" dataset.
3. Tokenize the dataset, adding the end-of-sentence token to each text.
4. Process the tokenized dataset into chunks of a specified block size.
Returns:
Dataset: The processed dataset ready for training.
"""
tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
dataset = load_dataset("openwebtext", split="train")
tokenized_dataset = dataset.map(
lambda example: tokenizer([t + tokenizer.eos_token for t in example["text"]]),
batched=True,
num_proc=CFG.NUM_CPU,
remove_columns=["text"],
)
block_size = CFG.SEQ_LEN
# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
# customize this part to your needs.
if total_length >= block_size:
total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated_examples.items()
}
return result
train_dataset = tokenized_dataset.map(
group_texts, batched=True, num_proc=CFG.NUM_CPU,
)
return train_dataset
#switch to falconwebdataset
def build_pre_tokenized():
d0 = load_dataset("conceptofmind/c4_0-to-20_neox_with_eos_8k", split="train[:10]")
# d1 = load_dataset("conceptofmind/c4_21-to-40_neox_with_eos_8k", split="train")
# d2 = load_dataset("conceptofmind/c4_41-to-60_neox_with_eos_8k", split="train")
# d3 = load_dataset("conceptofmind/c4_61-to-80_neox_with_eos_8k", split="train")
# d4 = load_dataset("conceptofmind/c4_81-to-100_neox_with_eos_8k", split="train")
# train_dataset = concatenate_datasets([d0, d1, d2, d3, d4])
return d0
def Train():
# accelerator
timeout = InitProcessGroupKwargs(timeout=timedelta(seconds=1_000_000))
accelerator = Accelerator(
gradient_accumulation_steps=CFG.GRADIENT_ACCUMULATE_EVERY,
mixed_precision="fp16",
log_with="wandb",
kwargs_handlers=[timeout],
)
state = AcceleratorState()
state.deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu'] = CFG.BATCH_SIZE #??????
accelerator.init_trackers(
project_name="Kosmos",
config={
"batch_size": CFG.BATCH_SIZE,
"gradient_accumulate_every": CFG.GRADIENT_ACCUMULATE_EVERY,
"learning_rate": CFG.LEARNING_RATE,
"seq_len": CFG.SEQ_LEN,
},
# init_kwargs={"wandb": {"entity": CFG.ENTITY_NAME}},
)
accelerator.print(f"Total GPUS: {accelerator.num_processes}")
# set seed
set_seed(CFG.SEED)
model = Kosmos()
print_num_params(model, accelerator)
if CFG.USE_FSDP:
model = fsdp(
model,
mp="fp16",
shard_strat="SHARD_GRAD"
)
if CFG.USE_ACTIVATION_CHECKPOINTING:
activation_checkpointing(model, accelerator)
model = accelerator.prepare(model)
# dataloaders
if CFG.USE_PRETOKENIZED:
train_dataset = build_pre_tokenized()
else:
train_dataset = build_dataloaders()
train_loader = DataLoader(
train_dataset, batch_size=CFG.BATCH_SIZE, collate_fn=default_data_collator,
)
# optimizer
optim = decoupled_optimizer(
model=model,
learning_rate=CFG.LEARNING_RATE,
weight_decay=CFG.WEIGHT_DECAY,
beta_1=0.90,
beta_2=0.95,
optimizer_type='lion',
use_fsdp=True,
accelerator=accelerator
)
# Determine number of training steps
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps: {max_train_steps}")
# lr scheduler
NUM_WARMUP_STEPS = int(max_train_steps * 0.01)
accelerator.print(f"Num warmup steps: {NUM_WARMUP_STEPS}")
# if False: # if CFG.USE_DEEPSPEED:
# lr_scheduler = DummyScheduler(
# optim,
# total_num_steps=max_train_steps * accelerator.num_processes,
# warmup_num_steps=NUM_WARMUP_STEPS
# )
# else:
lr_scheduler = get_lr_scheduler_with_warmup(
optimizer=optim,
scheduler_type="cosine",
num_warmup_steps=NUM_WARMUP_STEPS,
max_train_steps=max_train_steps,
grad_accumulate_every=CFG.GRADIENT_ACCUMULATE_EVERY,
)
# prepare
optim, train_loader, lr_scheduler = accelerator.prepare(
optim, train_loader, lr_scheduler
)
# checkpoint scheduler
accelerator.register_for_checkpointing(lr_scheduler)
# I do not know why Huggingface recommends recalculation of max_train_steps
max_train_steps = math.ceil(len(train_loader) / CFG.GRADIENT_ACCUMULATE_EVERY)
accelerator.print(f"Max train steps recalculated: {max_train_steps}")
# Total batch size for logging
total_batch_size = (
CFG.BATCH_SIZE * accelerator.num_processes * CFG.GRADIENT_ACCUMULATE_EVERY
)
accelerator.print(f"Total batch size: {total_batch_size}")
# resume training
progress_bar = tqdm(
range(max_train_steps), disable=not accelerator.is_local_main_process
)
completed_steps = 0
if CFG.RESUME_FROM_CHECKPOINT:
if CFG.RESUME_FROM_CHECKPOINT is not None or CFG.RESUME_FROM_CHECKPOINT != "":
accelerator.print(f"Resuming from checkpoint {CFG.RESUME_FROM_CHECKPOINT}")
accelerator.load_state(CFG.RESUME_FROM_CHECKPOINT)
path = os.path.basename(CFG.RESUME_FROM_CHECKPOINT)
training_difference = os.path.splitext(path)[0]
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = (
int(training_difference.replace("step_", ""))
* CFG.GRADIENT_ACCUMULATE_EVERY
)
if CFG.RESUME_FROM_CHECKPOINT and resume_step is not None:
train_loader = accelerator.skip_first_batches(train_loader, resume_step)
completed_steps += resume_step
progress_bar.update(resume_step)
# training
model.train()
for step, batch in enumerate(train_loader):
with accelerator.accumulate(model):
inputs = batch["input_ids"].to(accelerator.device)
loss = model(inputs, return_loss=True)
accelerator.backward(loss)
accelerator.log({"loss": loss.item()}, step=step)
if accelerator.sync_gradients:
accelerator.clip_grad_norm_(model.parameters(), 1.0)
optim.step()
lr_scheduler.step()
optim.zero_grad()
if accelerator.sync_gradients:
progress_bar.update(1)
completed_steps += 1
if isinstance(CFG.CHECKPOINTING_STEPS, int):
if completed_steps % CFG.CHECKPOINTING_STEPS == 0:
output_dir = f"step_{completed_steps }"
if CFG.OUTPUT_DIR is not None:
output_dir = os.path.join(CFG.OUTPUT_DIR, output_dir)
accelerator.save_state(output_dir)
if completed_steps >= max_train_steps:
break
#logging every CFG.LOGGING STEPS
if CFG.LOGGING_STEPS > 0 and step % CFG.LOGGING_STEPS == 0:
logger.info(
f"Step: {completed_steps}/{max_train_steps}, Loss: {loss.item():.5f}"
)
# end training
# accelerator.print(f"Training Finished")
accelerator.end_training()
# save final model
# accelerator.print(f"Saving model to {CFG.OUTPUT_DIR}")
if CFG.OUTPUT_DIR is not None:
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
with accelerator.main_process_first():
accelerator.save(
unwrapped_model.state_dict(), f"{CFG.OUTPUT_DIR}/final/final_model.pt"
)
def main():
os.environ['MASTER_ADDR'] #'localhost'
os.environ['MASTER_PORT'] #= '9994'
# # [CRITICAL] Pay attention to this when scaling to multiple GPUs and clusters
# # Pay attention to this, use "accelerate config"
os.environ['RANK'] #= str(0) # Number of nodes (servers)
os.environ['WORLD_SIZE'] # = str(torch.cuda.device_count())
dist.init_process_group(backend='nccl') #init_method="env://")
Train()
if __name__ == '__main__':
main() | Kosmos-X-master | kosmosx/train.py |
import argparse
import hidet
import torch
from einops._torch_specific import allow_ops_in_compiled_graph
from transformers import AutoTokenizer
def Inference():
allow_ops_in_compiled_graph()
torch.hub._validate_not_a_forked_repo = lambda a, b, c: True
parser = argparse.ArgumentParser(description="Generate text using PaLM model")
parser.add_argument("prompt", type=str, help="Text prompt to generate text")
parser.add_argument(
"--seq_len", type=int, default=256, help="Sequence length for generated text"
)
parser.add_argument(
"--temperature", type=float, default=0.8, help="Sampling temperature"
)
parser.add_argument(
"--filter_thres", type=float, default=0.9, help="Filter threshold for sampling"
)
parser.add_argument(
"--model",
type=str,
default="palm_1b_8k_v0",
help="Model to use for generation",
)
parser.add_argument(
"--dtype",
type=str,
default="fp32",
help="Data type for the model: 'bf16', or 'fp32'",
)
args = parser.parse_args()
dtype = torch.float32
if args.dtype == 'bf16':
dtype = torch.bfloat16
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = torch.hub.load("andromeda", args.model).to(device).to(dtype).eval()
hidet.torch.dynamo_config.use_tensor_core(True)
hidet.torch.dynamo_config.search_space(2)
opt_model = torch.compile(model, backend="hidet")
tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
encoded_text = tokenizer(args.prompt, return_tensors="pt")
output_tensor = opt_model.generate(
seq_len=args.seq_len,
prompt=encoded_text["input_ids"].to(device),
temperature=args.temperature,
filter_thres=args.filter_thres,
pad_value=0.0,
eos_token=tokenizer.eos_token_id,
return_seq_without_prompt=False,
use_tqdm=True,
)
decoded_output = tokenizer.batch_decode(output_tensor, skip_special_tokens=True)
return decoded_output
if __name__ == "__main__":
generated_text = Inference()
for text in generated_text:
print(f"{text}") | Kosmos-X-master | kosmosx/inference.py |
import argparse
import multiprocessing
from itertools import chain
from datasets import load_dataset
from kosmosx.model import KosmosTokenizer
class BuildDataset:
def __init__(self, seed=42, seq_len=8192, hf_account="YOUR HUGGINGFACE API KEY", dataset_name="uggingFaceM4/VQAv2"):
self.SEED = seed
self.SEQ_LEN = seq_len
self.NUM_CPU = multiprocessing.cpu_count()
self.HF_ACCOUNT_REPO = hf_account
self.DATASET_NAME = dataset_name
self.tokenizer = KosmosTokenizer.tokenize
def tokenize_function(self, example):
return self.tokenizer([t + self.tokenizer.eos_token for t in example["text"]])
def group_texts(self, examples):
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
if total_length >= self.SEQ_LEN:
total_length = (total_length // self.SEQ_LEN) * self.SEQ_LEN
result = {
k: [t[i : i + self.SEQ_LEN] for i in range(0, total_length, self.SEQ_LEN)]
for k, t in concatenated_examples.items()
}
return result
def build(self):
train_dataset = load_dataset(self.DATASET_NAME, split="train", streaming=True)
tokenized_dataset = train_dataset.map(
self.tokenize_function,
batched=True,
num_proc=self.NUM_CPU,
remove_columns=["text"],
)
train_tokenized_dataset = tokenized_dataset.map(
self.group_texts,
batched=True,
num_proc=self.NUM_CPU,
)
train_tokenized_dataset.push_to_hub(self.HF_ACCOUNT_REPO)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Process and push dataset to Hugging Face Hub")
parser.add_argument("--seed", type=int, default=42, help="Random seed")
parser.add_argument("--seq_len", type=int, default=8192, help="Sequence length for processing")
parser.add_argument("--hf_account", type=str, default="YOUR HUGGINGFACE API KEY", help="Hugging Face account name and repo")
parser.add_argument("--dataset_name", type=str, default="uggingFaceM4/VQAv2", help="Name of the dataset to process")
args = parser.parse_args()
dataset_builder = BuildDataset(seed=args.seed, seq_len=args.seq_len, hf_account=args.hf_account, dataset_name=args.dataset_name)
dataset_builder.build() | Kosmos-X-master | kosmosx/tokenize.py |
import torch
# This is the unfused version of StableAdamW. It is slower than the fused version (coming).
class StableAdamWUnfused(torch.optim.Optimizer):
def __init__(
self,
params,
lr=0.002,
weight_decay=0.2,
betas=(0.9, 0.99),
eps=1e-8,
clip_thresh=1.0,
precision="amp_bfloat16",
custom_scalar=65536,
):
beta1, beta2 = betas[0], betas[1]
defaults = dict(lr=lr, weight_decay=weight_decay, beta1=beta1, beta2=beta2)
super(StableAdamWUnfused, self).__init__(params, defaults)
self.eps = eps
self.d = clip_thresh
# Set precision to "custom_fp16" if you want to use a fixed loss scalar, custom_scalar, which is divided out in the update step.
# If you do this, call (custom_scalar * loss).backward() instead of loss.backward().
self.precision = precision
self.custom_scaler = custom_scalar
for group in self.param_groups:
group["step"] = 1.0
print("Using StableAdamWUnfused-v1")
def __setstate__(self, state):
super(StableAdamWUnfused, self).__setstate__(state)
def step(self, closure=None):
if closure is not None:
closure()
for group in self.param_groups:
lr = group["lr"]
weight_decay = group["weight_decay"]
beta1 = group["beta1"]
beta2 = group["beta2"]
step = group["step"]
for p in group["params"]:
if p.grad is None:
continue
theta = p.data
param_state = self.state[p]
if self.precision == "custom_fp16":
g = p.grad.data / self.custom_scaler
if torch.any(torch.isnan(g) | torch.isinf(g)):
continue
else:
g = p.grad.data
if "exp_avg" not in param_state:
v = param_state["exp_avg"] = torch.zeros_like(theta)
u = param_state["exp_avg_sq"] = torch.zeros_like(theta)
else:
v = param_state["exp_avg"]
u = param_state["exp_avg_sq"]
beta1hat = beta1 * (1 - beta1 ** (step - 1)) / (1 - beta1**step)
beta2hat = beta2 * (1 - beta2 ** (step - 1)) / (1 - beta2**step)
v = v.mul_(beta1hat).add_(g, alpha=1.0 - beta1hat)
u = u.mul_(beta2hat).addcmul_(g, g, value=1.0 - beta2hat)
denominator = u.sqrt().add_(self.eps)
# StableAdamW = AdamW + update clipping (https://arxiv.org/abs/1804.04235) applied tensor-wise.
rms = (
torch.div(
g.pow(2), torch.maximum(u, (self.eps**2) * torch.ones_like(u))
)
.mean()
.sqrt()
.item()
)
theta = theta.mul_(1.0 - lr * weight_decay).addcdiv_(
v, denominator, value=-lr * (1.0 / max(1.0, rms / self.d))
)
# save current params
param_state["exp_avg"] = v
param_state["exp_avg_sq"] = u
group["step"] = step + 1 | Kosmos-X-master | kosmosx/utils/stable_adamw.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
# T5 uses SentencePiece tokenizer
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>"],
extra_ids=0,
model_max_length=1984
)
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image tokens to text as "<s> <image> </image> text </s>"
image_tokens = torch.tensor([[self.im_idx, self.im_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], image_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
}
class Kosmos(Module):
def __init__(self):
super().__init__()
# Instantiate Clip Vit-l/14
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
multiway=True,
max_rel_pos=2048,
# flash_attention=True
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
def forward(self, text_tokens, images, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:2], images, model_input[:, 2:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/kosmos.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from transformers import Data2VecForCTC, Wav2Vec2Processor
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
#video
#preprecoess videos and tokenize them -> projection layer to transform the video features into the required embedding dimension
from torchvision import transforms
from torchvision.models.video import r3d_18
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
#video
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>", "<video>", "</video>"],
extra_ids=0,
model_max_length=1984
)
self.video_transform = transforms.Compose([
transforms.Resize((112, 112)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.43216, 0.394666, 0.37645], std=[0.22803, 0.22145, 0.216989])
])
self.vid_idx, self.vid_end_ix = self.tokenizer.convert_tokens_to_ids(["<video>", "</video>"])
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize_videos(self, videos):
processed_videos = []
for video in videos:
video_frames = [self.video_transform(frame) for frame in video]
processed_videos.append(torch.stack(video_frames))
return torch.stack(processed_videos)
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
"videos": self.tokenize_videos(sample["video"])
}
class Kosmos(Module):
def __init__(self):
super().__init__()
# Instantiate Clip Vit-l/14
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
#audio model
self.audio_model = Data2VecForCTC.from_pretrained("facebook/data2vec-audio-base-960h")
#video
self.video_model = r3d_18(pretrained=True)
self.video_model = torch.nn.Sequential(*list(self.video_model.children())[:-1])
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
# Process audio tokens
audios = self.audio_model(audios).logits
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
#process video tokens
videos = videos.transpose(1, 2).contigous()
videos = self.video_model(videos)
videos = videos.view(videos.size(0), -1)
videos = self.video_proj(videos)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:6], images, audios, videos, model_input[:, 6:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/video/kosmos_video.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from transformers import Data2VecForCTC, Wav2Vec2Processor
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
#video
#preprecoess videos and tokenize them -> projection layer to transform the video features into the required embedding dimension
import torchvision
class KosmosTokenizer:
def __init__(self, modalities=["text", "image", "audio", "video"]):
self.modalities = modalities
if "text" in modalities:
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>", "<video>", "</video>"],
extra_ids=0,
model_max_length=1984
)
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.vid_idx, self.vid_end_idx = self.tokenizer.convert_tokens_to_ids(["<video>", "</video>"])
if "image" in modalities:
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
if "audio" in modalities:
self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize_videos(self, videos):
processed_videos = []
for video in videos:
video_frames = [self.video_transform(frame) for frame in video]
processed_videos.append(torch.stack(video_frames))
return torch.stack(processed_videos)
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
tokenized_data = {
"text_tokens": text_tokens,
"labels": only_text_tokens,
"attention_mask": attention_mask
}
if "image" in self.modalities and "image" in sample:
tokenized_data["images"] = self.tokenize_images(sample["image"])
if "audio" in self.modalities and "audio" in sample:
tokenized_data["audios"] = self.tokenize_audio(sample["audio"])
if "video" in self.modalities and "video" in sample:
tokenized_data["videos"] = self.tokenize_videos(sample["video"])
return tokenized_data
class Kosmos(Module):
def __init__(self, modalities=["text", "image", "audio", "video"]):
super().__init__()
self.modalities = modalities
if "image" in modalities:
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.perceive = PerceiverResampler(
dim=1024,
depth=2,
dim_head=64,
heads=8,
num_latents=64,
num_media_embeds=257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
if "audio" in modalities:
self.audio_model = Data2VecForCTC.from_pretrained("facebook/data2vec-audio-base-960h")
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048**-0.5
)
if "video" in modalities:
# Load video model and preprocessor here
self.video_model = torchvision.models.video.r3d_18(pretrained=True)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048**-0.5
)
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, **kwargs):
model_input = self.decoder.forward_embedding(text_tokens)[1]
processed_modalities = [model_input[:, 0:6]]
if "images" in kwargs:
images = self.clip_model(pixel_values=kwargs["images"])["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
processed_modalities.append(images)
if "audios" in kwargs:
audios = self.audio_model(kwargs["audios"]).logits
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
processed_modalities.append(audios)
if "video" in self.modalities and "videos" in kwargs:
videos = kwargs["videos"].transpose(1, 2).contiguous()
videos = self.video_model(videos)
videos = videos.view(videos.size(0), -1)
videos = self.video_proj(videos)
processed_modalities.append(videos)
processed_modalities.append(model_input[:, 6:])
model_input = torch.cat(processed_modalities, dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0]
"""
You can initialize the KosmosTokenizer and Kosmos classes with any combination of modalities, such as:
tokenizer = KosmosTokenizer(modalities=["text", "image"])
model = Kosmos(modalities=["text", "image"])
Copy code
or
tokenizer = KosmosTokenizer(modalities=["text", "image", "audio", "video"])
model = Kosmos(modalities=["text", "image", "audio", "video"])
Copy code
The classes will handle the specified modalities during tokenization and processing.
""" | Kosmos-X-master | kosmosx/model/video/kosmos_conditional.py |
import torch
import data
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer
# from transformers import Data2VecForCTC, Wav2Vec2Processor
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
#video
#preprecoess videos and tokenize them -> projection layer to transform the video features into the required embedding dimension
# from torchvision.models.video import r3d_18
from Imagebind.models import imagebind_model
from ImageBind.models.imagebind_model import ModalityType
from Imagebind.models import imagebind_model
from Imagebind.models.imagebind_model import ModalityType
class KosmosTokenizer:
def __init__(self):
#tokenizers
# self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
# self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
#video ---> perhaps use falcon tokenizer if allow for special tokens
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>", "<video>", "</video>"],
extra_ids=0,
model_max_length=1984
)
# self.video_transform = transforms.Compose([
# transforms.Resize((112, 112)),
# transforms.ToTensor(),
# transforms.Normalize(mean=[0.43216, 0.394666, 0.37645], std=[0.22803, 0.22145, 0.216989])
# ])
self.vid_idx, self.vid_end_ix = self.tokenizer.convert_tokens_to_ids(["<video>", "</video>"])
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize_videos(self, videos):
processed_videos = []
for video in videos:
video_frames = [self.video_transform(frame) for frame in video]
processed_videos.append(torch.stack(video_frames))
return torch.stack(processed_videos)
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
"videos": self.tokenize_videos(sample["video"])
}
class Kosmos(Module):
def __init__(self):
super().__init__()
# embedding model
imagebind_model.imagebind_huge(pretrained=True)
{ModalityType.VISION : data.load_and_transform_vision_data(image_paths, device)}
{ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device)}
{ModalityType.VIDEO: data.load_and_transform_video_data(video_paths, device)}
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
multiway=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, **kwargs):
# images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.vision_embeddings(images)
images = self.image_proj(images)
# Process audio tokens
# audios = self.audio_model(audios).logits
audios = self.audio_embeddings(audios)
# audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
#process video tokens
# videos = videos.transpose(1, 2).contigous()
# videos = self.video_model(videos)
# videos = videos.view(videos.size(0), -1)
videos = self.video_embeddings(videos)
videos = self.video_proj(videos)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:6], images, audios, videos, model_input[:, 6:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/video/imagebind/kosmos.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import CLIPProcessor, CLIPModel, PreTrainedTokenizerFast
from tokenizers import SentencePieceBPETokenizer
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
# T5 uses SentencePiece tokenizer
# self.tokenizer = T5Tokenizer.from_pretrained(
# "t5-large",
# additional_special_tokens=["<image>", "</image>"],
# extra_ids=0,
# model_max_length=1984
# )
tokenizer = SentencePieceBPETokenizer.from_file("l")
self.tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
self.tokenizer.ad_special_tokens(["<image>", "</image>"])
self.tokenizer.model_max_length= 1984
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image tokens to text as "<s> <image> </image> text </s>"
image_tokens = torch.tensor([[self.im_idx, self.im_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], image_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
}
class Kosmos(Module):
def __init__(self):
super().__init__()
# Instantiate Clip Vit-l/14
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
def forward(self, text_tokens, images, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:2], images, model_input[:, 2:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/experiments/kosmosSP.py |
"""
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
"""
import os
import requests
import torch
from torch.nn import Module
from torchvision import transforms
from torchvision.models.video import r3d_18
from transformers import (
AutoModel,
AutoTokenizer,
CLIPModel,
CLIPProcessor,
Wav2Vec2ForCTC,
T5Tokenizer,
Wav2Vec2Processor,
)
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
import bitsandbytes
from flamingo_pytorch import PerceiverResampler
from concurrent.futures import ThreadPoolExecutor
class BaseTokenizer:
def tokenize(self, data):
raise NotImplementedError('This method should be implemented in a subclass')
def process(self, data):
raise NotImplementedError("This method should be implemented in a subclass")
def embed(self, data):
raise NotImplementedError("This method should be implemented in a subclass")
class ModalityDetector:
def __init__(self, method, input_data, user_input=None):
self.method = method
self.input_data = input_data
self.user_input = user_input
def get_modality(self):
if self.method == "file_extension":
return self.detect_modality_from_file_extension()
elif self.method == "content_based":
return self.detect_modality_from_content()
elif self.method == "user_input":
return self.user_input
def detect_modality_from_file_extension(self):
_, file_extension = os.path.splitext(self.input_data)
file_extension = file_extension.lower()
if file_extension in ['.jpg', '.jpeg', '.png', '.bmp']:
return 'image'
elif file_extension in ['.wav', '.mp3', '.ogg']:
return 'audio'
elif file_extension in [".txt", '.md', '.json']:
return 'text'
elif file_extension in ['.mp4', '.avi', '.mkv', '.mov']:
return 'video'
elif file_extension in ['.csv']:
return 'csv'
elif file_extension in ['.pdf']:
return 'pdf'
#add more modalities
def detect_modality_from_content(self):
#model that detects modalities or algo
pass
class TokenizerFactory:
def create_tokenizer(self, modality):
# Fetch models from Hugging Face API
api_url = "https://huggingface.co/api/models"
response = requests.get(api_url)
if response.status_code != 200:
raise ValueError("Failed to fetch models from Hugging Face API")
models = response.json()
# Filter models based on modality and sort by likes
matching_models = sorted(
[model for model in models if modality in model["tags"]],
key=lambda x: x["likes"],
reverse=True
)
if not matching_models:
raise ValueError(f"No matching tokenizer found for modality '{modality}'")
# Select the most liked tokenizer and instantiate it
selected_model = matching_models[0]["modelId"]
tokenizer = AutoTokenizer.from_pretrained(selected_model)
return tokenizer
class KosmosEmbedder(torch.nn.Module):
def __init__(self):
super().__init__()
self.models = {}
self.tokenizers = {}
self.projections = {}
def load_model(self, modality):
if modality not in self.models:
tokenizer = AutoTokenizer.from_pretrained(modality)
model = AutoModel.from_pretrained(modality)
proj = torch.nn.Linear(model.config.hidden_size, 2048)
self.tokenizers[modality] = tokenizer
self.models[modality] = model
self.projections[modality] = proj
def embed(self, modality, data):
self.load_model(modality)
tokenizer = self.tokenizers[modality]
model = self.models[modality]
proj = self.projections[modality]
tokens = tokenizer(data, return_tensors="pt", padding=True, truncation=True)
output = model(**tokens)
embed = proj(output.last_hidden_state)
return embed
class ModalityProcessor:
def __init__(self, modality_detector):
self.modality_detecor = modality_detector
self.modalities = {}
self.tokenizer_factory = TokenizerFactory(self.modality_detector)
self.executor = ThreadPoolExecutor()
def process(self, modality, data):
modality = self.modality_detector.get_modality()
if modality in self.modalities:
tokenizer = self.modalities[modality]
else:
tokenizer = self.tokenizer_factory.create_tokenizer(modality)
self.modalities[modality] = tokenizer
tokens = tokenizer(data, return_tensors="pt", padding=True, truncation=True)
return tokens
def process_parallel(self, modality_data_list):
results = []
for modality_data in modality_data_list:
modality = modality_data["modality"]
data = modality_data["data"]
result = self.executor.submit(self.process, modality, data)
results.append(result)
return [result.result() for result in results]
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>", "<video>", "</video>", "<any>", "</any>"],
extra_ids=0,
model_max_length=1984
)
self.video_transform = transforms.Compose([
transforms.Resize((112, 112)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.43216, 0.394666, 0.37645], std=[0.22803, 0.22145, 0.216989])
])
self.vid_idx, self.vid_end_ix = self.tokenizer.convert_tokens_to_ids(["<video>", "</video>"])
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.any_idx, self.any_end_idx = self.tokenizer.convert_tokens_to_ids(["<any>", "</any>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx, self.any_idx, self.any_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize_videos(self, videos):
if not videos:
return None
processed_videos = []
for video in videos:
video_frames = [self.video_transform(frame) for frame in video]
processed_videos.append(torch.stack(video_frames))
return torch.stack(processed_videos)
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
"videos": self.tokenize_videos(sample["video"])
}
class Kosmos(Module):
def __init__(self, modality, modality_detector):
super().__init__()
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.audio_model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
self.video_model = r3d_18(pretrained=True)
self.video_model = torch.nn.Sequential(*list(self.video_model.children())[:-1])
self.modality_detector = modality_detector
self.tokenizer = KosmosTokenizer()
self.processor = ModalityProcessor(modality_detector)
self.embedder = KosmosEmbedder(modality)
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, videos, any_modality, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
audios = self.audio_model(audios).logits
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
if videos is not None:
videos = videos.transpose(1, 2).contiguous()
videos = self.video_model(videos)
videos = videos.view(videos.size(0), -1)
videos = self.video_proj(videos)
any_embeddings = []
for modality_data in any_modality:
modality = modality_data["modality"]
data = modality_data["data"]
tokens = self.processor.processor(modality, data)
embed = self.embedder(modality)(tokens)
any_embeddings.append(embed)
any_embeddings = torch.stack(any_embeddings)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:6], images, audios, videos, any_embeddings, model_input[:, 6:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/allModalities/kosmos3.py |
import os
import requests
import torch
from torch.nn import Module
from torchvision import transforms
from torchvision.models.video import r3d_18
from transformers import (
AutoModel,
AutoTokenizer,
CLIPModel,
CLIPProcessor,
Wav2Vec2ForCTC,
T5Tokenizer,
Wav2Vec2Processor,
)
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
import bitsandbytes
from flamingo_pytorch import PerceiverResampler
class BaseTokenizer:
def tokenize(self, data):
raise NotImplementedError('This method should be implemented in a subclass')
def process(self, data):
raise NotImplementedError("This method should be implemented in a subclass")
def embed(self, data):
raise NotImplementedError("This method should be implemented in a subclass")
class ModalityDetector:
def __init__(self, method, input_data, user_input=None):
self.method = method
self.input_data = input_data
self.user_input = user_input
def get_modality(self):
if self.method == "file_extension":
return self.detect_modality_from_file_extension()
elif self.method == "content_based":
return self.detect_modality_from_content()
elif self.method == "user_input":
return self.user_input
def detect_modality_from_file_extension(self):
_, file_extension = os.path.splitext(self.input_data)
file_extension = file_extension.lower()
if file_extension in ['.jpg', '.jpeg', '.png', '.bmp']:
return 'image'
elif file_extension in ['.wav', '.mp3', '.ogg']:
return 'audio'
elif file_extension in [".txt", '.md', '.json']:
return 'text'
def detect_modality_from_content(self):
pass
class TokenizerFactory:
def create_tokenizer(self, modality):
# Fetch models from Hugging Face API
api_url = "https://huggingface.co/api/models"
response = requests.get(api_url)
if response.status_code != 200:
raise ValueError("Failed to fetch models from Hugging Face API")
models = response.json()
# Filter models based on modality and sort by likes
matching_models = sorted(
[model for model in models if modality in model["tags"]],
key=lambda x: x["likes"],
reverse=True
)
if not matching_models:
raise ValueError(f"No matching tokenizer found for modality '{modality}'")
# Select the most liked tokenizer and instantiate it
selected_model = matching_models[0]["modelId"]
tokenizer = AutoTokenizer.from_pretrained(selected_model)
return tokenizer
class ModalityProcessor:
def __init__(self, modality_detector):
self.modality_detector = modality_detector
self.modalities = {}
self.tokenizer_factory = TokenizerFactory(self.modality_detector)
def processor(self, modality, data):
modality = self.modality_detector.get_modality()
if modality in self.modalities:
tokenizer = self.modalities[modality]
else:
tokenizer = self.tokenizer_factory.create_tokenizer(modality)
self.modalities[modality] = tokenizer
tokens = tokenizer(data, return_tensors="pt", padding=True, truncation=True)
return tokens
class KosmosEmbedder(torch.nn.Module):
def __init__(self, modality):
super().__init__()
self.modality = modality
self.tokenizer = AutoTokenizer.from_pretrained(modality)
self.model = AutoModel.from_pretrained(modality)
self.proj = torch.nn.Linear(self.model.config.hidden_size, 2048)
def forward(self, data):
tokens = self.tokenizer(data, return_tensors="pt", padding=True, truncation=True)
output = self.model(**tokens)
embed = self.proj(output.last_hidden_state)
return embed
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>", "<video>", "</video>", "<any>", "</any>"],
extra_ids=0,
model_max_length=1984
)
self.video_transform = transforms.Compose([
transforms.Resize((112, 112)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.43216, 0.394666, 0.37645], std=[0.22803, 0.22145, 0.216989])
])
self.vid_idx, self.vid_end_ix = self.tokenizer.convert_tokens_to_ids(["<video>", "</video>"])
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.any_idx, self.any_end_idx = self.tokenizer.convert_tokens_to_ids(["<any>", "</any>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx, self.any_idx, self.any_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize_videos(self, videos):
if not videos:
return None
processed_videos = []
for video in videos:
video_frames = [self.video_transform(frame) for frame in video]
processed_videos.append(torch.stack(video_frames))
return torch.stack(processed_videos)
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
"videos": self.tokenize_videos(sample["video"])
}
class Kosmos(Module):
def __init__(self, modality, modality_detector):
super().__init__()
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.audio_model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
self.video_model = r3d_18(pretrained=True)
self.video_model = torch.nn.Sequential(*list(self.video_model.children())[:-1])
self.modality_detector = modality_detector
self.tokenizer = KosmosTokenizer()
self.processor = ModalityProcessor(modality_detector)
self.embedder = KosmosEmbedder(modality)
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, videos, any_modality, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
audios = self.audio_model(audios).logits
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
if videos is not None:
videos = videos.transpose(1, 2).contiguous()
videos = self.video_model(videos)
videos = videos.view(videos.size(0), -1)
videos = self.video_proj(videos)
any_embeddings = []
for modality_data in any_modality:
modality = modality_data["modality"]
data = modality_data["data"]
tokens = self.processor.processor(modality, data)
embed = self.embedder(modality)(tokens)
any_embeddings.append(embed)
any_embeddings = torch.stack(any_embeddings)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:6], images, audios, videos, any_embeddings, model_input[:, 6:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/allModalities/kosmos2.py |
import os
import torch
from torch.nn import Module
from torchvision import transforms
from torchvision.models.video import r3d_18
from transformers import (
AutoModel,
AutoTokenizer,
CLIPModel,
CLIPProcessor,
Data2VecForCTC,
T5Tokenizer,
Wav2Vec2Processor,
list_models
)
# Add additional imports
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
import bitsandbytes
from flamingo_pytorch import PerceiverResampler
# Import the ModalityDetector and other required classes
# from modality_detector import ModalityDetector, ModalityProcessor, TokenizerFactory
# from kosmos import Kosmos, KosmosEmbedder, KosmosTokenizer
#baseclass should contain the core methods for tokenizing processing and embedding input data
class BaseTokenizer:
def tokenize(self, data):
raise NotImplementedError('This method should be implemented in a subclass')
def process(self, data):
raise NotImplementedError("This method should be implemented in a subclass")
def embed(self, data):
raise NotImplementedError("This method should be implemented in a subclass")
class ModalityDetector:
def __init__(self, method, input_data, user_input=None):
self.method = method
self.input_data = input_data
self.user_input = user_input
def get_modality(self):
if self.method == "file_extension":
return self.detect_modality_from_file_extension()
elif self.method == "content_based":
return self.detect_modality_from_content()
elif self.method == "user_input":
return self.user_input
def detect_modality_from_file_extension(self):
_, file_extension = os.path.splitext(self.input_data)
file_extension = file_extension.lower()
if file_extension in ['.jpg', '.jpeg', '.png', '.bmp']:
return 'image'
elif file_extension in ['.wav', '.mp3', '.ogg']:
return 'audio'
elif file_extension in [".txt", '.md', '.json']:
return 'text'
def detect_modality_from_content(self):
# implement logic to determine modality based on content analysis
# this part requires a content-based modality detection model or algo
pass
class TokenizerFactory:
def __init__(self, modality_detector):
self.modality_detector = modality_detector
def create_tokenizer(self, modality):
modality = self.modality_detector.get_modality()
# search for pretrained tokenizers for the given modality
matching_models = list_models(filter=modality)
if not matching_models:
raise ValueError("No matching Tokenizer for modality")
# select the first matching tokenizer and instante it [make selection more favorable with most liked]
selected_model = matching_models[0]
tokenizer = AutoTokenizer.from_pretrained(selected_model)
return tokenizer
class ModalityProcessor:
def __init__(self, modality_detector):
self.modality_detector = modality_detector
self.modalities = {}
self.tokenizer_factory = TokenizerFactory(self.modality_detector)
def processor(self, modality, data):
modality = self.modality_detector.get_modality()
# Check if the modality is already registered
if modality in self.modalities:
tokenizer = self.modalities[modality]
else:
tokenizer = self.tokenizer_factory.create_tokenizer(modality)
self.modalities[modality] = tokenizer
tokens = tokenizer(data, return_tensors="pt", padding=True, truncation=True)
return tokens
class KosmosEmbedder(torch.nn.Module):
def __init__(self, modality):
super().__init__()
self.modality = modality
self.tokenizer = AutoTokenizer.from_pretrained(modality)
self.model = AutoModel.from_pretrained(modality)
self.proj = torch.nn.Linear(self.model.config.hidden_size, 2048)
def forward(self, data):
tokens = self.tokenizer(data, return_tensors="pt", padding=True, truncation=True)
output = self.model(**tokens)
embed = self.proj(output.last_hidden_state)
return embed
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
#video
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>", "<video>", "</video>", "<any>", "</any>"],
extra_ids=0,
model_max_length=1984
)
self.video_transform = transforms.Compose([
transforms.Resize((112, 112)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.43216, 0.394666, 0.37645], std=[0.22803, 0.22145, 0.216989])
])
self.vid_idx, self.vid_end_ix = self.tokenizer.convert_tokens_to_ids(["<video>", "</video>"])
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.any_idx, self.any_end_idx = self.tokenizer.convert_tokens_to_ids(["<any>", "</any>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
# media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx, self.any_idx, self.any_end_idx]] * texts.shape[0])
# return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx, self.vid_idx, self.vid_end_idx, self.any_idx, self.any_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize_videos(self, videos):
processed_videos = []
for video in videos:
video_frames = [self.video_transform(frame) for frame in video]
processed_videos.append(torch.stack(video_frames))
return torch.stack(processed_videos)
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
"videos": self.tokenize_videos(sample["video"])
}
class Kosmos(Module):
def __init__(self, modality, modality_detector):
super().__init__()
# Instantiate Clip Vit-l/14
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
#audio model
self.audio_model = Data2VecForCTC.from_pretrained("facebook/data2vec-audio-base-960h")
#video
self.video_model = r3d_18(pretrained=True)
self.video_model = torch.nn.Sequential(*list(self.video_model.children())[:-1])
self.modality_detector = modality_detector
self.tokenizer = KosmosTokenizer()
self.processor = ModalityProcessor(modality_detector)
self.embedder = KosmosEmbedder(modality)
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
self.video_proj = torch.nn.Linear(512, 2048, bias=False)
torch.nn.init.normal_(
self.video_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, videos, any_modality, **kwargs):
modality = self.modality_detector.get_modality(data)
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
# Process audio tokens
audios = self.audio_model(audios).logits
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
#process video tokens
videos = videos.transpose(1, 2).contigous()
videos = self.video_model(videos)
videos = videos.view(videos.size(0), -1)
videos = self.video_proj(videos)
#process any modality
any_embeddings = []
for modality_data in any_modality:
modality = modality_data["modality"]
data = modality_data["data"]
tokens = self.processor.processor(modality, data)
embed = self.embedder(modality)(tokens)
any_embeddings.append(embed)
any_embeddings = torch.stack(any_embeddings)
#v1
# Concatenate text tokens and media tokens
# model_input = self.decoder.forward_embedding(text_tokens)[1]
# model_input = torch.cat([model_input[:, 0:6], images, audios, videos, model_input[:, 6:]], dim=1)
# model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
#v2 any modality tokens
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:6], images, audios, videos, any_embeddings, model_input[:, 6:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0]
# return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/allModalities/kosmos.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from transformers import Wav2Vec2Tokenizer
from transformers import Wav2Vec2Model
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
# T5 uses SentencePiece tokenizer
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>"],
extra_ids=0,
model_max_length=1984
)
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.audio_tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h")
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_ids
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
}
class Kosmos(Module):
def __init__(self):
super().__init__()
# Instantiate Clip Vit-l/14
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.audio_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
#add audio
self.audio_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
#process audio tokens
audios = self.audio_model(input_ids=audios).last_hidden_state
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:3], images, audios, model_input[:, 3:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/allModalities/audio/kosmos_audio.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from transformers import Data2VecForCTC, Wav2Vec2Processor
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self):
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
self.audio_tokenizer = Wav2Vec2Processor.from_pretrained("facebook/data2vec-audio-base-960h")
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>"],
extra_ids=0,
model_max_length=1984
)
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_values
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
dummy_image_features = torch.ones((text_tokens.shape[0], 64))
attention_mask = torch.cat([dummy_image_features, attention_mask], dim=1)
return {
"text_tokens": text_tokens,
"images": self.tokenize_images(sample["image"]),
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": self.tokenize_audio(sample["audio"]),
}
class Kosmos(Module):
def __init__(self):
super().__init__()
# Instantiate Clip Vit-l/14
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
#audio model
self.audio_model = Data2VecForCTC.from_pretrained("facebook/data2vec-audio-base-960h")
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, **kwargs):
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
# Process audio tokens
audios = self.audio_model(audios).logits
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:3], images, audios, model_input[:, 3:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0] | Kosmos-X-master | kosmosx/model/allModalities/audio/kosmos_audio_data2vec.py |
import torch
from torchscale.architecture.config import DecoderConfig
from torchscale.architecture.decoder import Decoder
from torchscale.component.embedding import PositionalEmbedding
from transformers import T5Tokenizer, CLIPProcessor, CLIPModel
from transformers import Wav2Vec2Tokenizer
from transformers import Wav2Vec2Model
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self, modalities=["text", "image", "audio"]):
self.modalities = modalities
self.processor = CLIPProcessor.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K")
# T5 uses SentencePiece tokenizer
self.tokenizer = T5Tokenizer.from_pretrained(
"t5-large",
additional_special_tokens=["<image>", "</image>", "<audio>", "</audio>"],
extra_ids=0,
model_max_length=1984
)
self.audio_idx, self.audio_end_idx = self.tokenizer.convert_tokens_to_ids(["<audio>", "</audio>"])
self.im_idx, self.im_end_idx = self.tokenizer.convert_tokens_to_ids(["<image>", "</image>"])
self.audio_tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h")
def tokenize_texts(self, texts):
texts = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True).input_ids
# Add image and audio tokens to text as "<s> <image> </image> <audio> </audio> text </s>"
media_tokens = torch.tensor([[self.im_idx, self.im_end_idx, self.audio_idx, self.audio_end_idx]] * texts.shape[0])
return torch.cat([texts[:, 0:1], media_tokens, texts[:, 1:]], dim=1), texts
def tokenize_images(self, images):
return self.processor(images=images, return_tensors="pt").pixel_values
def tokenize_audio(self, audios):
return self.audio_tokenizer(audios, return_tensors="pt", padding=True, truncation=True).input_ids
def tokenize(self, sample):
text_tokens, only_text_tokens = self.tokenize_texts(sample["target_text"])
attention_mask = text_tokens != self.tokenizer.pad_token_id
if "image" in self.modalities:
images = self.tokenize_images(sample["image"])
else:
images = None
if "audio" in self.modalities:
audios = self.tokenize_audio(sample["audio"])
else:
audios = None
return {
"text_tokens": text_tokens,
"images": images,
"labels": only_text_tokens,
"attention_mask": attention_mask,
"audios": audios,
}
class Kosmos(Module):
def __init__(self, modalities=["text", "image", "audio"]):
super().__init__()
# Instantiate Clip Vit-l/14
self.modalities = modalities
self.clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-L-14-laion2B-s32B-b82K").vision_model
self.audio_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
self.embed = bitsandbytes.nn.modules.Embedding(
32002,
2048,
padding_idx=1
)
self.embed_positions= PositionalEmbedding(
2048,
2048,
1
)
self.output_projection = torch.nn.Linear(
2048, 32002, bias=False
)
torch.nn.init.normal_(
self.output_projection.weight, mean=0, std=2048**-0.5
)
# Config following KOSMOS-1 paper (https://arxiv.org/pdf/2302.14045.pdf)
self.config = DecoderConfig(
decoder_layers=24,
decoder_embed_dim=2048,
decoder_ffn_embed_dim=8192,
decoder_attention_heads=32,
dropout=0.1,
activation_fn="gelu",
attention_dropout=0.1,
vocab_size=64007,
subln=True,
xpos_rel_pos=True,
max_rel_pos=2048
)
self.decoder = Decoder(
self.config,
embed_tokens=self.embed,
embed_positions=self.embed_positions,
output_projection=self.output_projection
)
self.perceive = PerceiverResampler(
dim = 1024,
depth = 2,
dim_head = 64,
heads = 8,
num_latents = 64,
num_media_embeds = 257
)
self.image_proj = torch.nn.Linear(1024, 2048, bias=False)
torch.nn.init.normal_(
self.image_proj.weight, mean=0, std=2048**-0.5
)
#add audio
self.audio_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
self.audio_proj = torch.nn.Linear(768, 2048, bias=False)
torch.nn.init.normal_(
self.audio_proj.weight, mean=0, std=2048 ** -0.5
)
def forward(self, text_tokens, images, audios, **kwargs):
if "image" in self.modalities:
images = self.clip_model(pixel_values=images)["last_hidden_state"]
images = self.perceive(images).squeeze(1)
images = self.image_proj(images)
if "audio" in self.modalities:
audios = self.audio_model(input_ids=audios).last_hidden_state
audios = audios.mean(dim=1)
audios = self.audio_proj(audios)
model_input = self.decoder.forward_embedding(text_tokens)[1]
model_input = torch.cat([model_input[:, 0:3], images, audios, model_input[:, 3:]], dim=1)
model_input = self.decoder.forward_embedding(model_input, token_embedding=model_input)[0]
return self.decoder(model_input, passed_x=model_input)[0]
| Kosmos-X-master | kosmosx/model/allModalities/audio/kosmos_conditional.py |
import torch
import time
from torchinfo import summary
from pytorch_memlab import LineProfiler
from kosmosx.torchscale.torchscale.component.multihead_attention import MultiheadAttention
def test_multihead_attention():
batch_size = 64
d_model = 512
num_heads = 8
multihead_attention = MultiheadAttention(
embed_dim=d_model,
num_heads=num_heads,
dropout=0.1,
flash_attn=True
)
# Choose a set of sequence lengths to test
sequence_lengths = [2**n for n in range(10, 16)] # 1024, 2048, ..., 32768
for seq_len in sequence_lengths:
print(f'Testing sequence length: {seq_len}')
# Create some dummy data
query = torch.rand(batch_size, seq_len, d_model)
key = torch.rand(batch_size, seq_len, d_model)
value = torch.rand(batch_size, seq_len, d_model)
# Time the forward pass
start_time = time.time()
multihead_attention(query, key, value)
end_time = time.time()
print(f'Time taken for forward pass: {end_time - start_time} seconds')
# Compute the FLOPs
flops = summary(multihead_attention, input_size=(batch_size, seq_len, d_model))
print(f'FLOPs: {flops.total_ops}')
# Compute the memory usage
profiler = LineProfiler()
profiler.add_function(multihead_attention.forward)
profiler.add_module(multihead_attention)
profiler.run('output = multihead_attention(query, key, value)')
print('Memory usage: ', profiler.display())
test_multihead_attention()
| Kosmos-X-master | testing/attention.py |
import torch
from kosmosx.model import Kosmos
# Create a sample text token tensor
text_tokens = torch.randint(0, 32002, (1, 50), dtype=torch.long)
# Create a sample image tensor
images = torch.randn(1, 3, 224, 224)
# Instantiate the model
model = Kosmos()
# Pass the sample tensors to the model's forward function
output = model.forward(
text_tokens=text_tokens,
images=images
)
# Print the output from the model
print(f"Output: {output}") | Kosmos-X-master | testing/model_test.py |
import unittest
import torch
from kosmosx.model import Kosmos, KosmosTokenizer
from kosmosx.utils.stable_adamw import StableAdamWUnfused
class KosmosTest(unittest.TestCase):
def setUp(self):
self.model = Kosmos()
self.tokenizer = KosmosTokenizer()
self.optimizer = StableAdamWUnfused(self.model.parameters())
self.loss_function = torch.nn.CrossEntropyLoss()
self.input_text = ["<image>", "</image>"]
self.input_images = torch.randn(1, 3, 224, 224)
def test_forward_pass(self):
tokenized_input = self.tokenizer.tokenize_texts(self.input_text)
output = self.model(*tokenized_input, self.input_images)
self.assertEqual(output.shape, (1, 1024, 64007)) #verify output shape
def test_backward_pass(self):
self.optimizer.zero_grad()
tokenized_input = self.tokenizer.tokenize_texts(self.input_text)
output = self.model(*tokenized_input, self.input_images)
loss = self.loss_function(output.squeeze(), tokenized_input[0])
loss.backward()
for name, parameter in self.model_parameters():
self.assertFalse(torch.isnan(parameter.grad).any(), f"Gradient for {name} contains NaNs")
self.assertFalse(torch.isinf(parameter.grad).any(), f"Gradient for {name} contains Infs")
def test_optimizer_step(self):
initial_params = [param.clone() for param in self.model.parameters()]
tokenized_input = self.tokenizer.tokenize_texts(self.input_text)
output = self.model(*tokenized_input, self.input_images)
loss = self.loss_function(output.squeeze(), tokenized_input[0])
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
for initial_param, param in zip(initial_params, self.model.parameters()):
self.assertFalse(torch.equal(initial_param, param), 'Model parameters did not change after an optimizer step')
def test_data_loader(self):
pass
def test_lr_scheduling_rate(self):
pass
def test_hardware_compatibility(self):
#implement a hward capabiloty test here
pass
def test_reproducibility(self):
pass
if __name__ == "__main__":
unittest.main()
| Kosmos-X-master | testing/main.py |
import matplotlib.pyplot as plt
import time
import torch
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import numpy as np
import tracemalloc
from kosmosx.model import Kosmos
from kosmosx.utils.stable_adamw import StableAdamWUnfused
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class KosmosModelTest:
def __init__(self):
self.model = Kosmos
self.optimizer = StableAdamWUnfused()
self.loss_function = torch.nn.CrossEntropyLoss()
self.test_input = torch.randint(0, 256, (1, 1024)).cuda()
def test_forward_pass(self):
output = self.model(self.test_input)
assert output.shape == (1, 1024, 64007), "Forward pass output shape mismatch"
def test_backward_pass(self):
self.optimizer.zero_grad()
output = self.model(self.test_input)
loss = self.loss_function(output, self.test_input)
loss.backward()
for name, parameter in self.model.named_parameters():
assert not torch.isnan(parameter.grad().any()), f"Gradient for {name} contains NaNs"
assert not torch.isinf(parameter.grad().any()), f"Gradient for {name} contains Infs"
def test_optimizer_step(self):
initial_params = [param.clone() for param in self.model_parameters()]
output = self.model(self.test_input)
loss = self.loss_function(output, self.test_input)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
for initial_param, param in zip(initial_params, self.model.parameters()):
assert not torch.equal(initial_param, param), "Model Parameters did not change after an optimizer step"
class SpeedMetrics:
def __init__(self, model):
self.model = model.to(device)
def forward_pass_time(self):
start_time = time.time()
self.model.decoder.forward(torch.randint(0, 50304, (1, 8192), device=device, dtype=torch.long))[0]
end_time = time.time()
return end_time - start_time
def backward_pass_time(self):
model_input = self.model.decoder.forward(torch.randint(0, 50304, (1, 8192), device=device, dtype=torch.long))[0]
start_time = time.time()
loss = torch.nn.CrossEntropyLoss()(model_input, torch.randint(0, 50304, (1, 8192), device=device, dtype=torch.long))
loss.backward()
end_time = time.time()
return end_time - start_time
def end_to_end_latency(self):
start_time = time.time()
self.model.forward(torch.randint(0, 50304, (1, 8192), device=device, dtype=torch.long))
end_time = time.time()
return end_time - start_time
class ScalabilityMetrics:
def __init__(self, model, dataset):
self.model = model
self.dataset = dataset
self.dataloader = DataLoader(dataset, batch_size=32)
def throughput(self):
start_time = time.time()
for i, data in enumerate(self.dataloader, 0):
self.model.forward(data)
end_time = time.time()
return len(self.dataset) / (end_time - start_time)
class ConsistencyMetrics:
def __init__(self, model):
self.model = model
def consistency_over_time(self):
consistency_times = []
outputs_list = []
for _ in range(10):
start_time = time.time()
outputs = self.model.forward(torch.randint(0, 50304, (1, 8192)))
end_time = time.time()
consistency_times.append(end_time - start_time)
outputs_list.append(outputs.detach().numpy())
initial_output = outputs_list[0]
consistency_score = 0
for output in outputs_list[1:]:
if np.array_equal(initial_output, output):
consistency_score += 1
consistency_score = consistency_score / len(outputs_list) * 100
return consistency_times, consistency_score
class MemoryMetrics:
def __init__(self, model):
self.model = model
def memory_footprint(self):
tracemalloc.start()
self.model.forward(torch.randint(0, 50304, (1, 8192)))
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current, peak
class SequenceMetrics:
def __init__(self, model):
self.model = model
def sequence_length_impact(self):
seq_lengths = [1024, 2048, 4096, 8192]
seq_impact_times = []
for length in seq_lengths:
start_time = time.time()
self.model.forward(torch.randint(0, 50304, (1, length)))
end_time = time.time()
seq_impact_times.append(end_time - start_time)
return seq_lengths, seq_impact_times
class FlopsBenchmark:
def __init__(self, model, bsz=32, d_model=1024, num_heads=8, sequence_lengths=list(range(500, 32001, 500))):
self.bsz = bsz
self.d_model = d_model
self.num_heads = num_heads
self.sequence_lengths = sequence_lengths
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.dtype=torch.float32
self.model = model.to(self.device)
def benchmark(self):
time_taken = []
tflops_per_s = []
for seq_len in self.sequence_lengths:
x = torch.randn(self.bsz, seq_len, self.d_model).to(self.device).type(self.dtype)
torch.cuda.synchronize()
start = time.time()
self.model(x)
torch.cuda.synchronize()
elapsed = time.time() - start
time_taken.append(elapsed)
total_flops = 4 * seq_len **2 * (self.d_model // self.num_heads) * self.num_heads
tflops_per_s.append(total_flops / elapsed / 1e12) # Convert to TFLOPs
for seq_len, elapsed, tflops in zip(self.sequence_lengths, time_taken, tflops_per_s):
print(f"Sequence length: {seq_len}, Time elapsed: {elapsed} s, TFLOPs/s: {tflops}")
# import torch.nn.functional as F
# from nltk.translate.bleu_score import corpus_bleu
# from rouge import Rouge
# from sklearn.metrics import f1_score
# class AccuracyMetrics:
# def __init__(self):
# self.rouge = Rouge()
# def calculate_perplexity(self, model, data_loader):
# model.eval()
# total_loss = 0
# with torch.no_grad():
# for batch in data_loader:
# input_ids, labels = batch
# output = model(input_ids)
# loss = F.cross_entropy(output.view(-1, output.size(-1)), labels.view(-1))
# total_loss += loss.item()
# return torch.exp(torch.tensor(total_loss / len(data_loader)))
# def calculate_bleu(self, references, hypotheses):
# return corpus_bleu(references, hypotheses)
# def calculate_rouge(self, references, hypotheses):
# scores = self.rouge.get_scores(hypotheses, references, avg=True)
# return scores
# def calculate_f1(self, true_labels, pred_labels):
# return f1_score(true_labels, pred_labels, average="weighted")
#mock test dataset
test_dataset = datasets.FakeData(size=1000, transform=transforms.ToTensor())
#model
model = Kosmos(
num_tokens=50304,
dim=1024,
depth=24,
dim_head=128,
heads=8,
alibi_num_heads=4
)
#speed test metrics test
# speed test metrics test
speed_metrics = SpeedMetrics(model)
forward_pass_time = speed_metrics.forward_pass_time()
backward_pass_time = speed_metrics.backward_pass_time()
end_to_end_latency = speed_metrics.end_to_end_latency()
#scalability metrics test
scalability_metrics = ScalabilityMetrics(model, test_dataset)
throughput = scalability_metrics.throughput()
#consistency metrucs test
consistency_metrics = ConsistencyMetrics(model)
consistency_times, consistency_score = consistency_metrics.consistency_over_time()
#memory metrics test
memory_metrics = MemoryMetrics(model)
current, peak = memory_metrics.memory_footprint()
#sequence metrics test
sequence_metrics = SequenceMetrics(model)
seq_lengths, seq_impact_times = sequence_metrics.sequence_length_impact()
# # Usage:
# accuracy_metrics = AccuracyMetrics()
# # Calculate Perplexity
# perplexity = accuracy_metrics.calculate_perplexity(model, data_loader)
# print('Perplexity:', perplexity)
# # Calculate BLEU
# bleu = accuracy_metrics.calculate_bleu(references, hypotheses)
# print('BLEU Score:', bleu)
# # Calculate ROUGE
# rouge_scores = accuracy_metrics.calculate_rouge(references, hypotheses)
# print('ROUGE Scores:', rouge_scores)
# # Calculate F1 Score
# f1 = accuracy_metrics.calculate_f1(true_labels, pred_labels)
# print('F1 Score:', f1)
#flops
flops_benchmark = FlopsBenchmark(model)
flops_benchmark.benchmark()
# Graphical Interface
fig, axs = plt.subplots(3)
axs[0].bar(["Forward Pass Time", "Backward Pass Time", "End-to-End Latency"], [forward_pass_time, backward_pass_time, end_to_end_latency])
axs[0].set_title('Speed Metrics')
axs[0].set_xlabel('Metrics')
axs[0].set_ylabel('Time (seconds)')
axs[1].bar(seq_lengths, seq_impact_times)
axs[1].set_title('Sequence Length Impact')
axs[1].set_xlabel('Sequence Length')
axs[1].set_ylabel('Time (seconds)')
axs[2].plot(list(range(1, 11)), consistency_times)
axs[2].set_title('Consistency Over Time')
axs[2].set_xlabel('Run Number')
axs[2].set_ylabel('Time (seconds)')
plt.tight_layout()
plt.show()
print(f"Throughput: {throughput} instances/second")
print(f"Memory used: {current / 10**6}MB; Peak: {peak / 10**6}MB")
# Add at the bottom of your file
if __name__ == "__main__":
model_test = KosmosModelTest()
model_test.test_forward_pass()
model_test.test_backward_pass()
model_test.test_optimizer_step() | Kosmos-X-master | testing/benchmarking.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""Run pytest using MCP."""
import argparse
import time
from mcli.sdk import (RunConfig, RunStatus, create_run, follow_run_logs,
stop_run, wait_for_run_status)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--name',
type=str,
default='mcp-pytest',
help='Base name of run')
parser.add_argument('--cluster',
type=str,
default='r1z4',
help='Cluster to use')
parser.add_argument('--gpu_type',
type=str,
default='a100_40gb',
help='Type of GPU to use')
parser.add_argument('--gpu_num',
type=int,
default=2,
help='Number of the GPU to use')
parser.add_argument('--image',
type=str,
default='mosaicml/pytorch:latest',
help='Docker image to use')
parser.add_argument('--git_branch',
type=str,
help='Git branch to check out')
parser.add_argument(
'--git_commit',
type=str,
help='Git commit to check out. Overrides git_branch if specified')
parser.add_argument(
'--pr_number',
type=int,
help=
'PR number to check out. Overrides git_branch/git_commit if specified')
parser.add_argument('--pytest_markers',
type=str,
help='Markers to pass to pytest')
parser.add_argument('--pytest_command',
type=str,
help='Command to run pytest')
parser.add_argument('--timeout',
type=int,
default=1800,
help='Timeout for run (in seconds)')
args = parser.parse_args()
name = args.name
git_integration = {
'integration_type': 'git_repo',
'git_repo': 'mosaicml/llm-foundry',
'ssh_clone': 'False',
}
if args.git_branch is not None and args.git_commit is None:
name += f'-branch-{args.git_branch}'
git_integration['git_branch'] = args.git_branch
if args.git_commit is not None:
name += f'-commit-{args.git_commit}'
git_integration['git_commit'] = args.git_commit
command = 'cd llm-foundry'
# Checkout a specific PR if specified
if args.pr_number is not None:
name += f'-pr-{args.pr_number}'
command += f'''
git fetch origin pull/{args.pr_number}/head:pr_branch
git checkout pr_branch
'''
# Shorten name if too long
if len(name) > 56:
name = name[:56]
command += f'''
pip install --upgrade --user .[all]
export COMMON_ARGS="-v --durations=20 -m '{args.pytest_markers}'"
make test PYTEST='{args.pytest_command}' EXTRA_ARGS="$COMMON_ARGS --codeblocks"
make test-dist PYTEST='{args.pytest_command}' EXTRA_ARGS="$COMMON_ARGS" WORLD_SIZE=2
python -m coverage combine
python -m coverage report
'''
config = RunConfig(
name=name,
cluster=args.cluster,
gpu_type=args.gpu_type,
gpu_num=args.gpu_num,
image=args.image,
integrations=[git_integration],
command=command,
)
# Create run
run = create_run(config)
print(f'[GHA] Run created: {run.name}')
# Wait until run starts before fetching logs
run = wait_for_run_status(run, status='running')
start_time = time.time()
print('[GHA] Run started. Following logs...')
# Print logs
for line in follow_run_logs(run):
print(line, end='')
# Check if args.timeout seconds have elapsed
if time.time() - start_time > args.timeout:
print(
f'[GHA] Run timed out and did not complete in {args.timeout/60} minutes.'
)
run = stop_run(run)
print('[GHA] Run stopped.')
break
print('[GHA] Run completed. Waiting for run to finish...')
run = wait_for_run_status(run, status='completed')
# Fail if command exited with non-zero exit code or timed out
assert run.status == RunStatus.COMPLETED
| Kosmos-X-master | .github/mcp/mcp_pytest.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.