Upload projector/modeling_projector.py with huggingface_hub
Browse files
projector/modeling_projector.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers import PreTrainedModel
|
| 5 |
+
from transformers.activations import ACT2FN
|
| 6 |
+
|
| 7 |
+
from .configuration_projector import ProjectorConfig
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ProjectorModel(PreTrainedModel):
|
| 11 |
+
_auto_class = 'AutoModel'
|
| 12 |
+
config_class = ProjectorConfig
|
| 13 |
+
base_model_prefix = 'model'
|
| 14 |
+
supports_gradient_checkpointing = True
|
| 15 |
+
|
| 16 |
+
def __init__(self, config: ProjectorConfig) -> None:
|
| 17 |
+
super().__init__(config)
|
| 18 |
+
self.gradient_checkpointing = False
|
| 19 |
+
|
| 20 |
+
modules = [
|
| 21 |
+
nn.Linear(
|
| 22 |
+
config.visual_hidden_size,
|
| 23 |
+
config.llm_hidden_size,
|
| 24 |
+
bias=config.bias)
|
| 25 |
+
]
|
| 26 |
+
for _ in range(1, config.depth):
|
| 27 |
+
modules.append(ACT2FN[config.hidden_act])
|
| 28 |
+
modules.append(
|
| 29 |
+
nn.Linear(
|
| 30 |
+
config.llm_hidden_size,
|
| 31 |
+
config.llm_hidden_size,
|
| 32 |
+
bias=config.bias))
|
| 33 |
+
self.model = nn.Sequential(*modules)
|
| 34 |
+
|
| 35 |
+
def enable_input_require_grads(self):
|
| 36 |
+
|
| 37 |
+
def make_inputs_require_grad(module, input, output):
|
| 38 |
+
output.requires_grad_(True)
|
| 39 |
+
|
| 40 |
+
self.model.register_forward_hook(make_inputs_require_grad)
|
| 41 |
+
|
| 42 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 43 |
+
if isinstance(module, ProjectorModel):
|
| 44 |
+
module.gradient_checkpointing = value
|
| 45 |
+
|
| 46 |
+
def forward(self, x):
|
| 47 |
+
if self.gradient_checkpointing and self.training:
|
| 48 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(self.model, x)
|
| 49 |
+
else:
|
| 50 |
+
layer_outputs = self.model(x)
|
| 51 |
+
return layer_outputs
|