Run this model with HF Jobs
Run Lin-Chen/ShareCaptioner on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Lin-Chen/ShareCaptioner. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Lin-Chen/ShareCaptioner on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Lin-Chen/ShareCaptioner with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Lin-Chen/ShareCaptioner with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Lin-Chen/ShareCaptioner", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Lin-Chen/ShareCaptioner", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
chenlin commited on
Commit ·
a285f80
1
Parent(s): 60d2df3
fix import
Browse files1 unmodified line23456789101112139 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727346 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214 unmodified lines157158159160161162163323 unmodified lines487488489490491492493137 unmodified lines63163263363463563663758 unmodified lines69669769869970070170259 unmodified lines7627637647657667677687697707717727737747757767777787797807811 unmodified linefrom typing import List, Unionfrom typing import Optional, Tupleimport rotary_embimport torchimport torch.utils.checkpointimport torch.utils.checkpointfrom einops import rearrangefrom flash_attn.layers.rotary import ApplyRotaryEmbQKV_ as LegacyApplyRotaryEmbQKV_from torch import nnfrom torch.nn import CrossEntropyLossfrom transformers.activations import ACT2FN9 unmodified lines_CONFIG_FOR_DOC = "InternLMXComposerConfig"class ApplyRotaryEmbQKV_(torch.autograd.Function):"""ApplyRotaryEmbQKV_"""@staticmethoddef forward(ctx, qkv, cos, sin, cos_k=None, sin_k=None):"""qkv: (total, 3, nheads, headdim)cos, sin: (seqlen, rotary_dim / 2)cos_k, sin_k: (seqlen, rotary_dim / 2), optionalrotary_dim must be <= headdimApply rotary embedding *inplace* to the first rotary_dim of q and k."""_, three, _, headdim = qkv.shapeassert three == 3rotary_seqlen, rotary_dim = cos.shaperotary_dim *= 2assert rotary_dim <= headdimcos_k = cos if cos_k is None else cos_ksin_k = sin if sin_k is None else sin_kassert sin.shape == cos_k.shape == sin_k.shape == (rotary_seqlen,rotary_dim // 2)q1, q2 = qkv[:, 0, :, :rotary_dim].chunk(2, dim=-1)rotary_emb.apply_rotary(q1, q2, rearrange(cos, "s d -> s 1 d"),rearrange(sin, "s d -> s 1 d"), q1, q2, False)k1, k2 = qkv[:, 1, :, :rotary_dim].chunk(2, dim=-1)rotary_emb.apply_rotary(k1, k2, rearrange(cos_k, "s d -> s 1 d"),rearrange(sin_k, "s d -> s 1 d"), k1, k2,False)ctx.save_for_backward(cos, sin, cos_k, sin_k)return qkv@staticmethoddef backward(ctx, dqkv):cos, sin, cos_k, sin_k = ctx.saved_tensorsrotary_dim = cos.shape[-1]rotary_dim *= 2dq1, dq2 = dqkv[:, 0, :, :rotary_dim].chunk(2, dim=-1)rotary_emb.apply_rotary(dq1, dq2, rearrange(cos, "s d -> s 1 d"),rearrange(sin, "s d -> s 1 d"), dq1, dq2, True)dk1, dk2 = dqkv[:, 1, :, :rotary_dim].chunk(2, dim=-1)rotary_emb.apply_rotary(dk1, dk2, rearrange(cos_k, "s d -> s 1 d"),rearrange(sin_k, "s d -> s 1 d"), dk1, dk2,True)return dqkv, None, None, None, Noneclass ConvertedInternLMRotaryEmbedding(torch.nn.Module):46 unmodified linesself._cos_k_cached = (torch.cos(freqs) / scale).to(x.dtype)self._sin_k_cached = (torch.sin(freqs) / scale).to(x.dtype)def forward(self,qkv: torch.Tensor,indexes=0) -> Tuple[torch.Tensor, torch.Tensor]:self._update_cos_sin_cache(qkv, indexes)if self.scale is None:return apply_rotary_emb_qkv_(qkv, self._cos_cached[indexes],self._sin_cached[indexes]).to(qkv.dtype)else:return apply_rotary_emb_qkv_(qkv,self._cos_cached[indexes],self._sin_cached[indexes],self._cos_k_cached[indexes],self._sin_k_cached[indexes],).to(qkv.dtype)def eval_forward(self, qkv, seqlen_offset=0):"""seqlen_offset: can be used in generation where the qkv being passed in is only the last14 unmodified lines)apply_rotary_emb_qkv_ = ApplyRotaryEmbQKV_.applylegacy_apply_rotary_embed_qkv = LegacyApplyRotaryEmbQKV_.apply323 unmodified linesclass InternLMModel(InternLMPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLMDecoderLayer`]Args:config: InternLMXComposerConfig"""137 unmodified linespast_key_value = past_key_values[idx] if past_key_values is not None else Noneif self.gradient_checkpointing and self.training and idx % 2 == 0:def create_custom_forward(module):def custom_forward(*inputs):58 unmodified linessetattr(config, 'kqvo_bias', config.kqvo_bias)else:setattr(config, 'kqvo_bias', False)self.model = InternLMModel(config)self.lm_head = nn.Linear(config.hidden_size,59 unmodified linesLabels for computing the masked language modeling loss. Indices should either be in `[0, ...,config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.Returns:Example:```python>>> from transformers import AutoTokenizer, InternLMForCausalLM>>> model = InternLMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)>>> prompt = "Hey, are you consciours? Can you talk to me?">>> inputs = tokenizer(prompt, return_tensors="pt")>>> # Generate>>> generate_ids = model.generate(inputs.input_ids, max_length=30)>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]1 unmodified line2345678910119 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899046 unmodified lines13713813914014114214 unmodified lines157158159160161162323 unmodified lines486487488489490491137 unmodified lines62963063163263363463558 unmodified lines69469569669769869959 unmodified lines7597607617627637647657667677687697707717721 unmodified linefrom typing import List, Unionfrom typing import Optional, Tupleimport torchimport torch.utils.checkpointimport torch.utils.checkpointfrom einops import rearrangefrom torch import nnfrom torch.nn import CrossEntropyLossfrom transformers.activations import ACT2FN9 unmodified lines_CONFIG_FOR_DOC = "InternLMXComposerConfig"def rotary_embed(x1, x2, cos, sin, conj):x1, x2 = x1.float(), x2.float()if conj:x1, x2 = x1 * cos + x2 * sin, x1 * sin + x2 * coselse:x1, x2 = x1 * cos - x2 * sin, x1 * sin + x2 * cosreturn x1, x2class LegacyApplyRotaryEmbQKV_(torch.autograd.Function):@staticmethoddef forward(ctx, qkv, cos, sin, cos_k=None, sin_k=None, interleaved=False):"""qkv: (batch_size, seqlen, 3, nheads, headdim)cos, sin: (seqlen, rotary_dim / 2)cos_k, sin_k: (seqlen, rotary_dim / 2), optionalinterleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of1st half and 2nd half (GPT-NeoX style).rotary_dim must be <= headdimApply rotary embedding *inplace* to the first rotary_dim of q and k."""batch, seqlen, three, nheads, headdim = qkv.shapeassert three == 3rotary_seqlen, rotary_dim = cos.shaperotary_dim *= 2assert rotary_dim <= headdimassert seqlen <= rotary_seqlencos_k = cos if cos_k is None else cos_ksin_k = sin if sin_k is None else sin_kassert sin.shape == cos_k.shape == sin_k.shape == (rotary_seqlen, rotary_dim // 2)q_ro = qkv[:, :, 0, :, :rotary_dim]q1, q2 = q_ro.chunk(2, dim=-1) if not interleaved else (q_ro[..., ::2], q_ro[..., 1::2])# rotary_emb.apply_rotary(q1, q2, rearrange(cos[:seqlen], 's d -> s 1 d'),# rearrange(sin[:seqlen], 's d -> s 1 d'), q1, q2, False)q1, q2 = rotary_embed(q1, q2, rearrange(cos[:seqlen], 's d -> s 1 d'), rearrange(sin[:seqlen], 's d -> s 1 d'), False)qkv[:, :, 0, :, :rotary_dim] = torch.cat([q1, q2], dim=-1)k_ro = qkv[:, :, 1, :, :rotary_dim]k1, k2 = k_ro.chunk(2, dim=-1) if not interleaved else (k_ro[..., ::2], k_ro[..., 1::2])# rotary_emb.apply_rotary(k1, k2, rearrange(cos_k[:seqlen], 's d -> s 1 d'),# rearrange(sin_k[:seqlen], 's d -> s 1 d'), k1, k2, False)k1, k2 = rotary_embed(k1, k2, rearrange(cos_k[:seqlen], 's d -> s 1 d'), rearrange(sin_k[:seqlen], 's d -> s 1 d'), False)qkv[:, :, 1, :, :rotary_dim] = torch.cat([k1, k2], dim=-1)ctx.save_for_backward(cos, sin, cos_k, sin_k)ctx.interleaved = interleavedreturn qkv@staticmethoddef backward(ctx, dqkv):cos, sin, cos_k, sin_k = ctx.saved_tensors_, seqlen, _, _, headdim = dqkv.shaperotary_dim = cos.shape[-1]rotary_dim *= 2dq_ro = dqkv[:, :, 0, :, :rotary_dim]dq1, dq2 = (dq_ro.chunk(2, dim=-1) if not ctx.interleavedelse (dq_ro[..., ::2], dq_ro[..., 1::2]))rotary_emb.apply_rotary(dq1, dq2, rearrange(cos[:seqlen], 's d -> s 1 d'),rearrange(sin[:seqlen], 's d -> s 1 d'), dq1, dq2, True)dk_ro = dqkv[:, :, 1, :, :rotary_dim]dk1, dk2 = (dk_ro.chunk(2, dim=-1) if not ctx.interleavedelse (dk_ro[..., ::2], dk_ro[..., 1::2]))rotary_emb.apply_rotary(dk1, dk2, rearrange(cos_k[:seqlen], 's d -> s 1 d'),rearrange(sin_k[:seqlen], 's d -> s 1 d'), dk1, dk2, True)return dqkv, None, None, None, None, Noneclass ConvertedInternLMRotaryEmbedding(torch.nn.Module):46 unmodified linesself._cos_k_cached = (torch.cos(freqs) / scale).to(x.dtype)self._sin_k_cached = (torch.sin(freqs) / scale).to(x.dtype)def eval_forward(self, qkv, seqlen_offset=0):"""seqlen_offset: can be used in generation where the qkv being passed in is only the last14 unmodified lines)legacy_apply_rotary_embed_qkv = LegacyApplyRotaryEmbQKV_.apply323 unmodified linesclass InternLMModel(InternLMPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLMDecoderLayer`]Args:config: InternLMXComposerConfig"""137 unmodified linespast_key_value = past_key_values[idx] if past_key_values is not None else Noneif self.gradient_checkpointing and self.training:def create_custom_forward(module):def custom_forward(*inputs):58 unmodified linessetattr(config, 'kqvo_bias', config.kqvo_bias)else:setattr(config, 'kqvo_bias', False)self.model = InternLMModel(config)self.lm_head = nn.Linear(config.hidden_size,59 unmodified linesLabels for computing the masked language modeling loss. Indices should either be in `[0, ...,config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.Returns:Example:```python>>> from transformers import AutoTokenizer, InternLMForCausalLM>>> model = InternLMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)>>> prompt = "Hey, are you consciours? Can you talk to me?">>> inputs = tokenizer(prompt, return_tensors="pt")>>> # Generate>>> generate_ids = model.generate(inputs.input_ids, max_length=30)>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
modeling_InternLM.py+44-53