import json import logging import math from dataclasses import dataclass from pathlib…
- User
import json import logging import math from dataclasses import dataclass from pathlib import Path from typing import List, Optional
import torch from torch import nn from simple_parsing.helpers import Serializable
from mistral.rope import precompute_freqs_cis, apply_rotary_emb from mistral.cache import CacheView, RotatingBufferCache from mistral.moe import MoeArgs, MoeLayer
from xformers.ops.fmha import memory_efficient_attention
@dataclass class ModelArgs(Serializable): dim: int n_layers: int head_dim: int hidden_dim: int n_heads: int n_kv_heads: int norm_eps: float vocab_size: int
codemax_batch_size: int = 0 # For rotary embeddings. If not set, will be infered from sliding window. rope_theta: Optional[float] = None # If this is set, use sliding window attention rotating cache. sliding_window: Optional[int] = None # If this is set, we will use MoE layers instead of dense layers. moe: Optional[MoeArgs] = None@dataclass class SimpleInputMetadata: # rope absolute positions positions: torch.Tensor
code@staticmethod def from_seqlens(seqlens: List[int], device: torch.device) -> "SimpleInputMetadata": return SimpleInputMetadata( positions=torch.cat([torch.arange(0, seqlen) for seqlen in seqlens]).to( device=device, dtype=torch.long ) )def repeat_kv(keys: torch.Tensor, values: torch.Tensor, repeats: int, dim: int): keys = torch.repeat_interleave(keys, repeats=repeats, dim=dim) values = torch.repeat_interleave(values, repeats=repeats, dim=dim) return keys, values
class Attention(nn.Module): def init(self, args: ModelArgs): super().init() self.args = args
code - Assistant
- User
import dataclasses from typing import List
import torch import torch.nn.functional as F from simple_parsing.helpers import Serializable from torch import nn
@dataclasses.dataclass class MoeArgs(Serializable): num_experts: int num_experts_per_tok: int
class MoeLayer(nn.Module): def init(self, experts: List[nn.Module], gate: nn.Module, moe_args: MoeArgs): super().init() assert len(experts) > 0 self.experts = nn.ModuleList(experts) self.gate = gate self.args = moe_args
codedef forward(self, inputs: torch.Tensor): gate_logits = self.gate(inputs) weights, selected_experts = torch.topk(gate_logits, self.args.num_experts_per_tok) weights = F.softmax(weights, dim=1, dtype=torch.float).to(inputs.dtype) results = torch.zeros_like(inputs) for i, expert in enumerate(self.experts): batch_idx, nth_expert = torch.where(selected_experts == i) results[batch_idx] += weights[batch_idx, nth_expert, None] * expert( inputs[batch_idx] ) return results - Assistant
- User
define a function to define and train this neural network with transformer and MoE elements on a jsonl dataset with inputs and target keys, and add checkpointing to save the best model
- Assistant