Support transformers 5: call post_init() and recompute non-persistent buffers

#84
Files changed (1) hide show
  1. hf_moondream.py +24 -0
hf_moondream.py CHANGED
@@ -6,6 +6,7 @@ from typing import Union
6
 
7
  from .config import MoondreamConfig
8
  from .moondream import MoondreamModel
 
9
 
10
  # Files sometimes don't get loaded without these...
11
  from .image_crops import *
@@ -44,6 +45,29 @@ class HfMoondream(PreTrainedModel):
44
  MoondreamConfig.from_dict(config.config), setup_caches=False
45
  )
46
  self._is_kv_cache_setup = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  def _setup_caches(self):
49
  if not self._is_kv_cache_setup:
 
6
 
7
  from .config import MoondreamConfig
8
  from .moondream import MoondreamModel
9
+ from .rope import precompute_freqs_cis
10
 
11
  # Files sometimes don't get loaded without these...
12
  from .image_crops import *
 
45
  MoondreamConfig.from_dict(config.config), setup_caches=False
46
  )
47
  self._is_kv_cache_setup = False
48
+ self.post_init()
49
+
50
+ @torch.no_grad()
51
+ def _init_weights(self, module):
52
+ # transformers>=5 builds the model on the meta device, so non-persistent
53
+ # buffers are not loaded from the checkpoint and must be recomputed here.
54
+ if module is self.model:
55
+ config = self.model.config
56
+ max_context = config.text.max_context
57
+ patch_w = config.vision.crop_size // config.vision.enc_patch_size
58
+ prefix_attn_len = 1 + patch_w**2
59
+ attn_mask = torch.tril(
60
+ torch.ones(max_context, max_context, dtype=torch.bool)
61
+ )
62
+ attn_mask[:prefix_attn_len, :prefix_attn_len] = 1
63
+ module.attn_mask.copy_(attn_mask)
64
+ elif module is self.model.text:
65
+ config = self.model.config.text
66
+ module.freqs_cis.copy_(
67
+ precompute_freqs_cis(
68
+ config.dim // (2 * config.n_heads), config.max_context
69
+ )
70
+ )
71
 
72
  def _setup_caches(self):
73
  if not self._is_kv_cache_setup: