We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[tensor] fix some unittests

[tensor] fix some unittests

[tensor] fix some unittests


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `colossalai/shardformer/policies/opt.py`
Content:
```
1 import warnings
2 from functools import partial
3 from typing import Callable, Dict, List
4 
5 import torch.nn as nn
6 from torch import Tensor, nn
7 
8 from colossalai.shardformer.layer import FusedLayerNorm, Linear1D_Col, Linear1D_Row, VocabParallelEmbedding1D
9 
10 from .._utils import getattr_
11 from ..modeling.jit import get_jit_fused_dropout_add_func
12 from ..modeling.opt import OPTPipelineForwards, get_jit_fused_opt_decoder_layer_forward, get_opt_flash_attention_forward
13 from .base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription
14 
15 __all__ = [
16     'OPTPolicy', 'OPTModelPolicy', 'OPTForCausalLMPolicy', 'OPTForSequenceClassificationPolicy',
17     'OPTForQuestionAnsweringPolicy'
18 ]
19 
20 
21 class OPTPolicy(Policy):
22 
23     def config_sanity_check(self):
24         pass
25 
26     def preprocess(self):
27         # reshape the embedding layer
28         r"""
29         Reshape the Embedding layer to make the embedding dimension divisible by world_size
30         """
31         if self.shard_config.enable_tensor_parallelism:
32             vocab_size = self.model.config.vocab_size
33             world_size = self.shard_config.tensor_parallel_size
34             if vocab_size % world_size != 0:
35                 new_vocab_size = vocab_size + world_size - vocab_size % world_size
36                 self.model.resize_token_embeddings(new_vocab_size)
37         return self.model
38 
39     def module_policy(self):
40         from transformers.models.opt.modeling_opt import OPTAttention, OPTDecoder, OPTDecoderLayer
41 
42         policy = {}
43         if self.shard_config.enable_sequence_parallelism:
44             self.shard_config.enable_sequence_parallelism = False
45             warnings.warn("OPT dosen't support sequence parallelism now, will ignore the sequence parallelism flag.")
46 
47         if self.shard_config.enable_tensor_parallelism:
48             policy[OPTDecoder] = ModulePolicyDescription(sub_module_replacement=[
49                 SubModuleReplacementDescription(
50                     suffix="embed_tokens",
51                     target_module=VocabParallelEmbedding1D,
52                 )
53             ])
54             policy[OPTDecoderLayer] = ModulePolicyDescription(sub_module_replacement=[
55                 SubModuleReplacementDescription(
56                     suffix="fc1",
57                     target_module=Linear1D_Col,
58                 ),
59                 SubModuleReplacementDescription(
60                     suffix="fc2",
61                     target_module=Linear1D_Row,
62                 )
63             ])
64 
65             policy[OPTAttention] = ModulePolicyDescription(attribute_replacement={
66                 "embed_dim": self.model.config.hidden_size // self.shard_config.tensor_parallel_size,
67                 "num_heads": self.model.config.num_attention_heads // self.shard_config.tensor_parallel_size
68             },
69                                                            sub_module_replacement=[
70                                                                SubModuleReplacementDescription(
71                                                                    suffix="q_proj",
72                                                                    target_module=Linear1D_Col,
73                                                                ),
74                                                                SubModuleReplacementDescription(
75                                                                    suffix="k_proj",
76                                                                    target_module=Linear1D_Col,
77                                                                ),
78                                                                SubModuleReplacementDescription(
79                                                                    suffix="v_proj",
80                                                                    target_module=Linear1D_Col,
81                                                                ),
82                                                                SubModuleReplacementDescription(
83                                                                    suffix="out_proj",
84                                                                    target_module=Linear1D_Row,
85                                                                ),
86                                                            ])
87 
88         # optimization configuration
89         if self.shard_config.enable_fused_normalization:
90             self.append_or_create_submodule_replacement(description=SubModuleReplacementDescription(
91                 suffix="final_layer_norm", target_module=FusedLayerNorm, ignore_if_not_exist=True),
92                                                         policy=policy,
93                                                         target_key=OPTDecoder)
94             self.append_or_create_submodule_replacement(description=[
95                 SubModuleReplacementDescription(suffix="self_attn_layer_norm",
96                                                 target_module=FusedLayerNorm,
97                                                 ignore_if_not_exist=True),
98                 SubModuleReplacementDescription(suffix="final_layer_norm",
99                                                 target_module=FusedLayerNorm,
100                                                 ignore_if_not_exist=True)
101             ],
102                                                         policy=policy,
103                                                         target_key=OPTDecoderLayer)
104 
105         # use flash attention
106         if self.shard_config.enable_flash_attention:
107             self.append_or_create_method_replacement(description={
108                 'forward': get_opt_flash_attention_forward(),
109             },
110                                                      policy=policy,
111                                                      target_key=OPTAttention)
112 
113         # use jit fused operator
114         if self.shard_config.enable_jit_fused:
115             self.append_or_create_method_replacement(description={
116                 'forward': get_jit_fused_opt_decoder_layer_forward(),
117                 'dropout_add': get_jit_fused_dropout_add_func(),
118             },
119                                                      policy=policy,
120                                                      target_key=OPTDecoderLayer)
121 
122         return policy
123 
124     def postprocess(self):
125         return self.model
126 
127     def get_held_layers(self) -> List[nn.Module]:
128         """Get pipeline layers for current stage."""
129         assert self.pipeline_stage_manager is not None
130 
131         if self.model.__class__.__name__ == 'OPTModel':
132             module = self.model.decoder
133         else:
134             module = self.model.model.decoder
135         stage_manager = self.pipeline_stage_manager
136 
137         held_layers = []
138         layers_per_stage = self.distribute_layers(len(module.layers), stage_manager.num_stages)
139         if stage_manager.is_first_stage():
140             held_layers.append(module.embed_tokens)
141             held_layers.append(module.embed_positions)
142             held_layers.append(module.project_in)
143         start_idx, end_idx = self.get_stage_index(layers_per_stage, stage_manager.stage)
144         held_layers.extend(module.layers[start_idx:end_idx])
145         if stage_manager.is_last_stage():
146             held_layers.append(module.final_layer_norm)
147             held_layers.append(module.project_out)
148         return held_layers
149 
150     def set_pipeline_forward(self, model_cls: nn.Module, new_forward: Callable, policy: Dict) -> None:
151         """If under pipeline parallel setting, replacing the original forward method of huggingface
152            to customized forward method, and add this changing to policy."""
153         if self.pipeline_stage_manager:
154             stage_manager = self.pipeline_stage_manager
155             if self.model.__class__.__name__ == 'OPTModel':
156                 module = self.model.decoder
157             else:
158                 module = self.model.model.decoder
159 
160             layers_per_stage = Policy.distribute_layers(len(module.layers), stage_manager.num_stages)
161             stage_index = Policy.get_stage_index(layers_per_stage, stage_manager.stage)
162             method_replacement = {'forward': partial(new_forward, stage_manager=stage_manager, stage_index=stage_index)}
163             self.append_or_create_method_replacement(description=method_replacement,
164                                                      policy=policy,
165                                                      target_key=model_cls)
166 
167 
168 class OPTModelPolicy(OPTPolicy):
169 
170     def __init__(self) -> None:
171         super().__init__()
172 
173     def module_policy(self):
174         from transformers.models.opt.modeling_opt import OPTModel
175 
176         policy = super().module_policy()
177         if self.pipeline_stage_manager:
178             self.set_pipeline_forward(model_cls=OPTModel,
179                                       new_forward=OPTPipelineForwards.opt_model_forward,
180                                       policy=policy)
181         return policy
182 
183     def get_held_layers(self) -> List[nn.Module]:
184         return super().get_held_layers()
185 
186     def get_shared_params(self) -> List[Dict[int, Tensor]]:
187         """No shared params in OPTModel."""
188         return []
189 
190 
191 class OPTForCausalLMPolicy(OPTPolicy):
192 
193     def module_policy(self):
194         from transformers.models.opt.modeling_opt import OPTForCausalLM
195 
196         policy = super().module_policy()
197         if self.shard_config.enable_tensor_parallelism:
198             self.append_or_create_submodule_replacement(description=SubModuleReplacementDescription(
199                 suffix="lm_head", target_module=Linear1D_Col, kwargs=dict(gather_output=True)),
200                                                         policy=policy,
201                                                         target_key=OPTForCausalLM)
202         if self.pipeline_stage_manager:
203             self.set_pipeline_forward(model_cls=OPTForCausalLM,
204                                       new_forward=OPTPipelineForwards.opt_for_causal_lm_forward,
205                                       policy=policy)
206 
207         return policy
208 
209     def get_held_layers(self) -> List[nn.Module]:
210         held_layers = super().get_held_layers()
211         if self.pipeline_stage_manager.is_last_stage():
212             held_layers.append(self.model.lm_head)
213         return held_layers
214 
215     def get_shared_params(self) -> List[Dict[int, Tensor]]:
216         opt_model = self.model
217         if self.pipeline_stage_manager and self.pipeline_stage_manager.num_stages > 1:
218             num_stages = self.pipeline_stage_manager.num_stages
219             if id(opt_model.model.decoder.embed_tokens.weight) == id(opt_model.lm_head.weight):
220                 return [{0: opt_model.model.decoder.embed_tokens.weight, num_stages - 1: opt_model.lm_head.weight}]
221         return []
222 
223     def postprocess(self):
224         if self.shard_config.enable_tensor_parallelism and self.pipeline_stage_manager is None:
225             binding_map = {
226                 'model.decoder.embed_tokens': 'lm_head',
227             }
228 
229             for k, v in binding_map.items():
230                 src_mod = getattr_(self.model, k)
231                 dst_mod = getattr_(self.model, v)
232                 dst_mod.weight = src_mod.weight
233 
234         return self.model
235 
236 
237 class OPTForSequenceClassificationPolicy(OPTPolicy):
238 
239     def __init__(self) -> None:
240         super().__init__()
241 
242     def module_policy(self):
243         from transformers.models.opt.modeling_opt import OPTForSequenceClassification
244 
245         policy = super().module_policy()
246         if self.pipeline_stage_manager:
247             self.set_pipeline_forward(model_cls=OPTForSequenceClassification,
248                                       new_forward=OPTPipelineForwards.opt_for_sequence_classification_forward,
249                                       policy=policy)
250 
251         return policy
252 
253     def get_held_layers(self) -> List[nn.Module]:
254         held_layers = super().get_held_layers()
255         if self.pipeline_stage_manager.is_last_stage():
256             held_layers.append(self.model.score)
257         return held_layers
258 
259     def get_shared_params(self) -> List[Dict[int, Tensor]]:
260         "no shared params in OPTForSequenceClassification"
261         return []
262 
263 
264 class OPTForQuestionAnsweringPolicy(OPTPolicy):
265 
266     def __init__(self) -> None:
267         super().__init__()
268 
269     def module_policy(self):
270         from transformers.models.opt.modeling_opt import OPTForQuestionAnswering
271 
272         policy = super().module_policy()
273         if self.pipeline_stage_manager:
274             self.set_pipeline_forward(model_cls=OPTForQuestionAnswering,
275                                       new_forward=OPTPipelineForwards.opt_for_question_answering_forward,
276                                       policy=policy)
277 
278         return policy
279 
280     def get_held_layers(self) -> List[nn.Module]:
281         held_layers = super().get_held_layers()
282         if self.pipeline_stage_manager.is_last_stage():
283             held_layers.append(self.model.qa_outputs)
284         return held_layers
285 
286     def get_shared_params(self) -> List[Dict[int, Tensor]]:
287         "no shared params in OPTForSequenceClassification"
288         return []
289
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/colossalai/shardformer/policies/opt.py b/colossalai/shardformer/policies/opt.py
--- a/colossalai/shardformer/policies/opt.py
+++ b/colossalai/shardformer/policies/opt.py
@@ -103,21 +103,21 @@
                                                         target_key=OPTDecoderLayer)
 
         # use flash attention
-        if self.shard_config.enable_flash_attention:
-            self.append_or_create_method_replacement(description={
-                'forward': get_opt_flash_attention_forward(),
-            },
-                                                     policy=policy,
-                                                     target_key=OPTAttention)
+        # if self.shard_config.enable_flash_attention:
+        #     self.append_or_create_method_replacement(description={
+        #         'forward': get_opt_flash_attention_forward(),
+        #     },
+        #                                              policy=policy,
+        #                                              target_key=OPTAttention)
 
         # use jit fused operator
-        if self.shard_config.enable_jit_fused:
-            self.append_or_create_method_replacement(description={
-                'forward': get_jit_fused_opt_decoder_layer_forward(),
-                'dropout_add': get_jit_fused_dropout_add_func(),
-            },
-                                                     policy=policy,
-                                                     target_key=OPTDecoderLayer)
+        # if self.shard_config.enable_jit_fused:
+        #     self.append_or_create_method_replacement(description={
+        #         'forward': get_jit_fused_opt_decoder_layer_forward(),
+        #         'dropout_add': get_jit_fused_dropout_add_func(),
+        #     },
+        #                                              policy=policy,
+        #                                              target_key=OPTDecoderLayer)
 
         return policy

{"golden_diff": "diff --git a/colossalai/shardformer/policies/opt.py b/colossalai/shardformer/policies/opt.py\n--- a/colossalai/shardformer/policies/opt.py\n+++ b/colossalai/shardformer/policies/opt.py\n@@ -103,21 +103,21 @@\n                                                         target_key=OPTDecoderLayer)\n \n         # use flash attention\n-        if self.shard_config.enable_flash_attention:\n-            self.append_or_create_method_replacement(description={\n-                'forward': get_opt_flash_attention_forward(),\n-            },\n-                                                     policy=policy,\n-                                                     target_key=OPTAttention)\n+        # if self.shard_config.enable_flash_attention:\n+        #     self.append_or_create_method_replacement(description={\n+        #         'forward': get_opt_flash_attention_forward(),\n+        #     },\n+        #                                              policy=policy,\n+        #                                              target_key=OPTAttention)\n \n         # use jit fused operator\n-        if self.shard_config.enable_jit_fused:\n-            self.append_or_create_method_replacement(description={\n-                'forward': get_jit_fused_opt_decoder_layer_forward(),\n-                'dropout_add': get_jit_fused_dropout_add_func(),\n-            },\n-                                                     policy=policy,\n-                                                     target_key=OPTDecoderLayer)\n+        # if self.shard_config.enable_jit_fused:\n+        #     self.append_or_create_method_replacement(description={\n+        #         'forward': get_jit_fused_opt_decoder_layer_forward(),\n+        #         'dropout_add': get_jit_fused_dropout_add_func(),\n+        #     },\n+        #                                              policy=policy,\n+        #                                              target_key=OPTDecoderLayer)\n \n         return policy\n", "issue": "[tensor] fix some unittests\n\n[tensor] fix some unittests\n\n[tensor] fix some unittests\n\n", "before_files": [{"content": "import warnings\nfrom functools import partial\nfrom typing import Callable, Dict, List\n\nimport torch.nn as nn\nfrom torch import Tensor, nn\n\nfrom colossalai.shardformer.layer import FusedLayerNorm, Linear1D_Col, Linear1D_Row, VocabParallelEmbedding1D\n\nfrom .._utils import getattr_\nfrom ..modeling.jit import get_jit_fused_dropout_add_func\nfrom ..modeling.opt import OPTPipelineForwards, get_jit_fused_opt_decoder_layer_forward, get_opt_flash_attention_forward\nfrom .base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription\n\n__all__ = [\n    'OPTPolicy', 'OPTModelPolicy', 'OPTForCausalLMPolicy', 'OPTForSequenceClassificationPolicy',\n    'OPTForQuestionAnsweringPolicy'\n]\n\n\nclass OPTPolicy(Policy):\n\n    def config_sanity_check(self):\n        pass\n\n    def preprocess(self):\n        # reshape the embedding layer\n        r\"\"\"\n        Reshape the Embedding layer to make the embedding dimension divisible by world_size\n        \"\"\"\n        if self.shard_config.enable_tensor_parallelism:\n            vocab_size = self.model.config.vocab_size\n            world_size = self.shard_config.tensor_parallel_size\n            if vocab_size % world_size != 0:\n                new_vocab_size = vocab_size + world_size - vocab_size % world_size\n                self.model.resize_token_embeddings(new_vocab_size)\n        return self.model\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTAttention, OPTDecoder, OPTDecoderLayer\n\n        policy = {}\n        if self.shard_config.enable_sequence_parallelism:\n            self.shard_config.enable_sequence_parallelism = False\n            warnings.warn(\"OPT dosen't support sequence parallelism now, will ignore the sequence parallelism flag.\")\n\n        if self.shard_config.enable_tensor_parallelism:\n            policy[OPTDecoder] = ModulePolicyDescription(sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"embed_tokens\",\n                    target_module=VocabParallelEmbedding1D,\n                )\n            ])\n            policy[OPTDecoderLayer] = ModulePolicyDescription(sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"fc1\",\n                    target_module=Linear1D_Col,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"fc2\",\n                    target_module=Linear1D_Row,\n                )\n            ])\n\n            policy[OPTAttention] = ModulePolicyDescription(attribute_replacement={\n                \"embed_dim\": self.model.config.hidden_size // self.shard_config.tensor_parallel_size,\n                \"num_heads\": self.model.config.num_attention_heads // self.shard_config.tensor_parallel_size\n            },\n                                                           sub_module_replacement=[\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"q_proj\",\n                                                                   target_module=Linear1D_Col,\n                                                               ),\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"k_proj\",\n                                                                   target_module=Linear1D_Col,\n                                                               ),\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"v_proj\",\n                                                                   target_module=Linear1D_Col,\n                                                               ),\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"out_proj\",\n                                                                   target_module=Linear1D_Row,\n                                                               ),\n                                                           ])\n\n        # optimization configuration\n        if self.shard_config.enable_fused_normalization:\n            self.append_or_create_submodule_replacement(description=SubModuleReplacementDescription(\n                suffix=\"final_layer_norm\", target_module=FusedLayerNorm, ignore_if_not_exist=True),\n                                                        policy=policy,\n                                                        target_key=OPTDecoder)\n            self.append_or_create_submodule_replacement(description=[\n                SubModuleReplacementDescription(suffix=\"self_attn_layer_norm\",\n                                                target_module=FusedLayerNorm,\n                                                ignore_if_not_exist=True),\n                SubModuleReplacementDescription(suffix=\"final_layer_norm\",\n                                                target_module=FusedLayerNorm,\n                                                ignore_if_not_exist=True)\n            ],\n                                                        policy=policy,\n                                                        target_key=OPTDecoderLayer)\n\n        # use flash attention\n        if self.shard_config.enable_flash_attention:\n            self.append_or_create_method_replacement(description={\n                'forward': get_opt_flash_attention_forward(),\n            },\n                                                     policy=policy,\n                                                     target_key=OPTAttention)\n\n        # use jit fused operator\n        if self.shard_config.enable_jit_fused:\n            self.append_or_create_method_replacement(description={\n                'forward': get_jit_fused_opt_decoder_layer_forward(),\n                'dropout_add': get_jit_fused_dropout_add_func(),\n            },\n                                                     policy=policy,\n                                                     target_key=OPTDecoderLayer)\n\n        return policy\n\n    def postprocess(self):\n        return self.model\n\n    def get_held_layers(self) -> List[nn.Module]:\n        \"\"\"Get pipeline layers for current stage.\"\"\"\n        assert self.pipeline_stage_manager is not None\n\n        if self.model.__class__.__name__ == 'OPTModel':\n            module = self.model.decoder\n        else:\n            module = self.model.model.decoder\n        stage_manager = self.pipeline_stage_manager\n\n        held_layers = []\n        layers_per_stage = self.distribute_layers(len(module.layers), stage_manager.num_stages)\n        if stage_manager.is_first_stage():\n            held_layers.append(module.embed_tokens)\n            held_layers.append(module.embed_positions)\n            held_layers.append(module.project_in)\n        start_idx, end_idx = self.get_stage_index(layers_per_stage, stage_manager.stage)\n        held_layers.extend(module.layers[start_idx:end_idx])\n        if stage_manager.is_last_stage():\n            held_layers.append(module.final_layer_norm)\n            held_layers.append(module.project_out)\n        return held_layers\n\n    def set_pipeline_forward(self, model_cls: nn.Module, new_forward: Callable, policy: Dict) -> None:\n        \"\"\"If under pipeline parallel setting, replacing the original forward method of huggingface\n           to customized forward method, and add this changing to policy.\"\"\"\n        if self.pipeline_stage_manager:\n            stage_manager = self.pipeline_stage_manager\n            if self.model.__class__.__name__ == 'OPTModel':\n                module = self.model.decoder\n            else:\n                module = self.model.model.decoder\n\n            layers_per_stage = Policy.distribute_layers(len(module.layers), stage_manager.num_stages)\n            stage_index = Policy.get_stage_index(layers_per_stage, stage_manager.stage)\n            method_replacement = {'forward': partial(new_forward, stage_manager=stage_manager, stage_index=stage_index)}\n            self.append_or_create_method_replacement(description=method_replacement,\n                                                     policy=policy,\n                                                     target_key=model_cls)\n\n\nclass OPTModelPolicy(OPTPolicy):\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTModel\n\n        policy = super().module_policy()\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTModel,\n                                      new_forward=OPTPipelineForwards.opt_model_forward,\n                                      policy=policy)\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        return super().get_held_layers()\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        \"\"\"No shared params in OPTModel.\"\"\"\n        return []\n\n\nclass OPTForCausalLMPolicy(OPTPolicy):\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTForCausalLM\n\n        policy = super().module_policy()\n        if self.shard_config.enable_tensor_parallelism:\n            self.append_or_create_submodule_replacement(description=SubModuleReplacementDescription(\n                suffix=\"lm_head\", target_module=Linear1D_Col, kwargs=dict(gather_output=True)),\n                                                        policy=policy,\n                                                        target_key=OPTForCausalLM)\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTForCausalLM,\n                                      new_forward=OPTPipelineForwards.opt_for_causal_lm_forward,\n                                      policy=policy)\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        held_layers = super().get_held_layers()\n        if self.pipeline_stage_manager.is_last_stage():\n            held_layers.append(self.model.lm_head)\n        return held_layers\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        opt_model = self.model\n        if self.pipeline_stage_manager and self.pipeline_stage_manager.num_stages > 1:\n            num_stages = self.pipeline_stage_manager.num_stages\n            if id(opt_model.model.decoder.embed_tokens.weight) == id(opt_model.lm_head.weight):\n                return [{0: opt_model.model.decoder.embed_tokens.weight, num_stages - 1: opt_model.lm_head.weight}]\n        return []\n\n    def postprocess(self):\n        if self.shard_config.enable_tensor_parallelism and self.pipeline_stage_manager is None:\n            binding_map = {\n                'model.decoder.embed_tokens': 'lm_head',\n            }\n\n            for k, v in binding_map.items():\n                src_mod = getattr_(self.model, k)\n                dst_mod = getattr_(self.model, v)\n                dst_mod.weight = src_mod.weight\n\n        return self.model\n\n\nclass OPTForSequenceClassificationPolicy(OPTPolicy):\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTForSequenceClassification\n\n        policy = super().module_policy()\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTForSequenceClassification,\n                                      new_forward=OPTPipelineForwards.opt_for_sequence_classification_forward,\n                                      policy=policy)\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        held_layers = super().get_held_layers()\n        if self.pipeline_stage_manager.is_last_stage():\n            held_layers.append(self.model.score)\n        return held_layers\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        \"no shared params in OPTForSequenceClassification\"\n        return []\n\n\nclass OPTForQuestionAnsweringPolicy(OPTPolicy):\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTForQuestionAnswering\n\n        policy = super().module_policy()\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTForQuestionAnswering,\n                                      new_forward=OPTPipelineForwards.opt_for_question_answering_forward,\n                                      policy=policy)\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        held_layers = super().get_held_layers()\n        if self.pipeline_stage_manager.is_last_stage():\n            held_layers.append(self.model.qa_outputs)\n        return held_layers\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        \"no shared params in OPTForSequenceClassification\"\n        return []\n", "path": "colossalai/shardformer/policies/opt.py"}], "after_files": [{"content": "import warnings\nfrom functools import partial\nfrom typing import Callable, Dict, List\n\nimport torch.nn as nn\nfrom torch import Tensor, nn\n\nfrom colossalai.shardformer.layer import FusedLayerNorm, Linear1D_Col, Linear1D_Row, VocabParallelEmbedding1D\n\nfrom .._utils import getattr_\nfrom ..modeling.jit import get_jit_fused_dropout_add_func\nfrom ..modeling.opt import OPTPipelineForwards, get_jit_fused_opt_decoder_layer_forward, get_opt_flash_attention_forward\nfrom .base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription\n\n__all__ = [\n    'OPTPolicy', 'OPTModelPolicy', 'OPTForCausalLMPolicy', 'OPTForSequenceClassificationPolicy',\n    'OPTForQuestionAnsweringPolicy'\n]\n\n\nclass OPTPolicy(Policy):\n\n    def config_sanity_check(self):\n        pass\n\n    def preprocess(self):\n        # reshape the embedding layer\n        r\"\"\"\n        Reshape the Embedding layer to make the embedding dimension divisible by world_size\n        \"\"\"\n        if self.shard_config.enable_tensor_parallelism:\n            vocab_size = self.model.config.vocab_size\n            world_size = self.shard_config.tensor_parallel_size\n            if vocab_size % world_size != 0:\n                new_vocab_size = vocab_size + world_size - vocab_size % world_size\n                self.model.resize_token_embeddings(new_vocab_size)\n        return self.model\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTAttention, OPTDecoder, OPTDecoderLayer\n\n        policy = {}\n        if self.shard_config.enable_sequence_parallelism:\n            self.shard_config.enable_sequence_parallelism = False\n            warnings.warn(\"OPT dosen't support sequence parallelism now, will ignore the sequence parallelism flag.\")\n\n        if self.shard_config.enable_tensor_parallelism:\n            policy[OPTDecoder] = ModulePolicyDescription(sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"embed_tokens\",\n                    target_module=VocabParallelEmbedding1D,\n                )\n            ])\n            policy[OPTDecoderLayer] = ModulePolicyDescription(sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"fc1\",\n                    target_module=Linear1D_Col,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"fc2\",\n                    target_module=Linear1D_Row,\n                )\n            ])\n\n            policy[OPTAttention] = ModulePolicyDescription(attribute_replacement={\n                \"embed_dim\": self.model.config.hidden_size // self.shard_config.tensor_parallel_size,\n                \"num_heads\": self.model.config.num_attention_heads // self.shard_config.tensor_parallel_size\n            },\n                                                           sub_module_replacement=[\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"q_proj\",\n                                                                   target_module=Linear1D_Col,\n                                                               ),\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"k_proj\",\n                                                                   target_module=Linear1D_Col,\n                                                               ),\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"v_proj\",\n                                                                   target_module=Linear1D_Col,\n                                                               ),\n                                                               SubModuleReplacementDescription(\n                                                                   suffix=\"out_proj\",\n                                                                   target_module=Linear1D_Row,\n                                                               ),\n                                                           ])\n\n        # optimization configuration\n        if self.shard_config.enable_fused_normalization:\n            self.append_or_create_submodule_replacement(description=SubModuleReplacementDescription(\n                suffix=\"final_layer_norm\", target_module=FusedLayerNorm, ignore_if_not_exist=True),\n                                                        policy=policy,\n                                                        target_key=OPTDecoder)\n            self.append_or_create_submodule_replacement(description=[\n                SubModuleReplacementDescription(suffix=\"self_attn_layer_norm\",\n                                                target_module=FusedLayerNorm,\n                                                ignore_if_not_exist=True),\n                SubModuleReplacementDescription(suffix=\"final_layer_norm\",\n                                                target_module=FusedLayerNorm,\n                                                ignore_if_not_exist=True)\n            ],\n                                                        policy=policy,\n                                                        target_key=OPTDecoderLayer)\n\n        # use flash attention\n        # if self.shard_config.enable_flash_attention:\n        #     self.append_or_create_method_replacement(description={\n        #         'forward': get_opt_flash_attention_forward(),\n        #     },\n        #                                              policy=policy,\n        #                                              target_key=OPTAttention)\n\n        # use jit fused operator\n        # if self.shard_config.enable_jit_fused:\n        #     self.append_or_create_method_replacement(description={\n        #         'forward': get_jit_fused_opt_decoder_layer_forward(),\n        #         'dropout_add': get_jit_fused_dropout_add_func(),\n        #     },\n        #                                              policy=policy,\n        #                                              target_key=OPTDecoderLayer)\n\n        return policy\n\n    def postprocess(self):\n        return self.model\n\n    def get_held_layers(self) -> List[nn.Module]:\n        \"\"\"Get pipeline layers for current stage.\"\"\"\n        assert self.pipeline_stage_manager is not None\n\n        if self.model.__class__.__name__ == 'OPTModel':\n            module = self.model.decoder\n        else:\n            module = self.model.model.decoder\n        stage_manager = self.pipeline_stage_manager\n\n        held_layers = []\n        layers_per_stage = self.distribute_layers(len(module.layers), stage_manager.num_stages)\n        if stage_manager.is_first_stage():\n            held_layers.append(module.embed_tokens)\n            held_layers.append(module.embed_positions)\n            held_layers.append(module.project_in)\n        start_idx, end_idx = self.get_stage_index(layers_per_stage, stage_manager.stage)\n        held_layers.extend(module.layers[start_idx:end_idx])\n        if stage_manager.is_last_stage():\n            held_layers.append(module.final_layer_norm)\n            held_layers.append(module.project_out)\n        return held_layers\n\n    def set_pipeline_forward(self, model_cls: nn.Module, new_forward: Callable, policy: Dict) -> None:\n        \"\"\"If under pipeline parallel setting, replacing the original forward method of huggingface\n           to customized forward method, and add this changing to policy.\"\"\"\n        if self.pipeline_stage_manager:\n            stage_manager = self.pipeline_stage_manager\n            if self.model.__class__.__name__ == 'OPTModel':\n                module = self.model.decoder\n            else:\n                module = self.model.model.decoder\n\n            layers_per_stage = Policy.distribute_layers(len(module.layers), stage_manager.num_stages)\n            stage_index = Policy.get_stage_index(layers_per_stage, stage_manager.stage)\n            method_replacement = {'forward': partial(new_forward, stage_manager=stage_manager, stage_index=stage_index)}\n            self.append_or_create_method_replacement(description=method_replacement,\n                                                     policy=policy,\n                                                     target_key=model_cls)\n\n\nclass OPTModelPolicy(OPTPolicy):\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTModel\n\n        policy = super().module_policy()\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTModel,\n                                      new_forward=OPTPipelineForwards.opt_model_forward,\n                                      policy=policy)\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        return super().get_held_layers()\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        \"\"\"No shared params in OPTModel.\"\"\"\n        return []\n\n\nclass OPTForCausalLMPolicy(OPTPolicy):\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTForCausalLM\n\n        policy = super().module_policy()\n        if self.shard_config.enable_tensor_parallelism:\n            self.append_or_create_submodule_replacement(description=SubModuleReplacementDescription(\n                suffix=\"lm_head\", target_module=Linear1D_Col, kwargs=dict(gather_output=True)),\n                                                        policy=policy,\n                                                        target_key=OPTForCausalLM)\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTForCausalLM,\n                                      new_forward=OPTPipelineForwards.opt_for_causal_lm_forward,\n                                      policy=policy)\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        held_layers = super().get_held_layers()\n        if self.pipeline_stage_manager.is_last_stage():\n            held_layers.append(self.model.lm_head)\n        return held_layers\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        opt_model = self.model\n        if self.pipeline_stage_manager and self.pipeline_stage_manager.num_stages > 1:\n            num_stages = self.pipeline_stage_manager.num_stages\n            if id(opt_model.model.decoder.embed_tokens.weight) == id(opt_model.lm_head.weight):\n                return [{0: opt_model.model.decoder.embed_tokens.weight, num_stages - 1: opt_model.lm_head.weight}]\n        return []\n\n    def postprocess(self):\n        if self.shard_config.enable_tensor_parallelism and self.pipeline_stage_manager is None:\n            binding_map = {\n                'model.decoder.embed_tokens': 'lm_head',\n            }\n\n            for k, v in binding_map.items():\n                src_mod = getattr_(self.model, k)\n                dst_mod = getattr_(self.model, v)\n                dst_mod.weight = src_mod.weight\n\n        return self.model\n\n\nclass OPTForSequenceClassificationPolicy(OPTPolicy):\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTForSequenceClassification\n\n        policy = super().module_policy()\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTForSequenceClassification,\n                                      new_forward=OPTPipelineForwards.opt_for_sequence_classification_forward,\n                                      policy=policy)\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        held_layers = super().get_held_layers()\n        if self.pipeline_stage_manager.is_last_stage():\n            held_layers.append(self.model.score)\n        return held_layers\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        \"no shared params in OPTForSequenceClassification\"\n        return []\n\n\nclass OPTForQuestionAnsweringPolicy(OPTPolicy):\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def module_policy(self):\n        from transformers.models.opt.modeling_opt import OPTForQuestionAnswering\n\n        policy = super().module_policy()\n        if self.pipeline_stage_manager:\n            self.set_pipeline_forward(model_cls=OPTForQuestionAnswering,\n                                      new_forward=OPTPipelineForwards.opt_for_question_answering_forward,\n                                      policy=policy)\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        held_layers = super().get_held_layers()\n        if self.pipeline_stage_manager.is_last_stage():\n            held_layers.append(self.model.qa_outputs)\n        return held_layers\n\n    def get_shared_params(self) -> List[Dict[int, Tensor]]:\n        \"no shared params in OPTForSequenceClassification\"\n        return []\n", "path": "colossalai/shardformer/policies/opt.py"}]}