PENNe-pytorch 0.0.2__tar.gz → 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ from functools import lru_cache, partial
4
4
  from math import log, pi, sqrt
5
5
 
6
6
  import torch
7
- from torch import arange, cat, stack, where, Tensor
7
+ from torch import arange, cat, stack, tensor, where, Tensor
8
8
  from torch.autograd import grad
9
9
  from torch.nn import Module, ModuleList, Linear, Embedding, Parameter, GELU
10
10
  import torch.nn.functional as F
@@ -28,7 +28,7 @@ import torch_geometric
28
28
  import einx
29
29
  from einops import rearrange, repeat, reduce, einsum, pack, unpack
30
30
 
31
- from torch_einops_utils import device_dtype, exclusive_cumprod
31
+ from torch_einops_utils import device_dtype, exclusive_cumprod, pack_with_inverse
32
32
  from torch_einops_utils.shape import shape, size
33
33
 
34
34
  from x_mlps_pytorch import MLP
@@ -86,6 +86,29 @@ def resolve_cutoffs(
86
86
  assert not exists(depth) or len(cutoffs) == depth, f'expected {depth} cutoffs, got {len(cutoffs)}'
87
87
  return cutoffs
88
88
 
89
+ def is_atomic_num(v):
90
+ return isinstance(v, int) and not isinstance(v, bool) and v >= 0
91
+
92
+ def resolve_moe_atomic_nums(
93
+ atomic_nums: int | tuple[int | tuple[int, ...], ...] | None
94
+ ) -> tuple[tuple[int, ...], ...]:
95
+ if not exists(atomic_nums):
96
+ return ()
97
+
98
+ if isinstance(atomic_nums, int):
99
+ atomic_nums = (atomic_nums,)
100
+
101
+ groups = tuple(
102
+ (item,) if isinstance(item, int) else tuple(item)
103
+ for item in atomic_nums
104
+ )
105
+
106
+ flat = [z for group in groups for z in group]
107
+ assert all(len(g) > 0 for g in groups), 'moe expert group cannot be empty'
108
+ assert all(is_atomic_num(z) for z in flat), 'atomic numbers must be non-negative ints'
109
+ assert len(flat) == len(set(flat)), 'duplicate atomic numbers across moe experts'
110
+ return groups
111
+
89
112
  def eval_poly(x: Tensor, coeffs: tuple[float, ...]):
90
113
  powers = exclusive_cumprod(repeat(x, '... -> ... p', p = len(coeffs)))
91
114
  return einsum(powers, x.new_tensor(coeffs), '... p, p -> ...')
@@ -522,36 +545,50 @@ class FourierRadialBasis(Module):
522
545
  angles = einx.multiply('..., f -> ... f', distances * (pi / self.cutoff), self.freqs)
523
546
  return einx.multiply('... f, ... -> ... f', angles.sin(), envelope)
524
547
 
525
- class TwoExpertMLP(Module):
548
+ class MoEMLP(Module):
526
549
  def __init__(
527
550
  self,
528
551
  *dims,
552
+ num_experts = 1,
529
553
  activation = None
530
554
  ):
531
555
  super().__init__()
556
+ assert num_experts >= 1, 'num_experts must be at least 1'
557
+
532
558
  activation = default(activation, GELU())
533
- self.dim_out = dims[-1]
534
- self.heavy_expert = MLP(*dims, activation = activation)
535
- self.hydrogen_expert = MLP(*dims, activation = activation)
559
+ self.num_experts = num_experts
560
+ self.experts = ModuleList([MLP(*dims, activation = activation) for _ in range(num_experts)])
536
561
 
537
562
  def forward(
538
563
  self,
539
564
  x: Tensor,
540
- is_hydrogen: Tensor | None = None
565
+ expert_ids: Tensor | None = None
541
566
  ):
542
- if not exists(is_hydrogen) or not is_hydrogen.any():
543
- return self.heavy_expert(x)
567
+ if self.num_experts == 1 or not exists(expert_ids):
568
+ return self.experts[0](x)
569
+
570
+ assert x.shape[:-1] == expert_ids.shape
571
+ x_flat, inverse_pack = pack_with_inverse(x, '* d')
572
+
573
+ if x_flat.shape[0] == 0:
574
+ return self.experts[0](x)
575
+
576
+ expert_ids_flat = expert_ids.reshape(-1).long()
577
+ counts = torch.bincount(expert_ids_flat, minlength = self.num_experts).tolist()
578
+ assert len(counts) == self.num_experts, f'expert_ids must be in [0, {self.num_experts - 1}]'
544
579
 
545
- if is_hydrogen.all():
546
- return self.hydrogen_expert(x)
580
+ active = [i for i, count in enumerate(counts) if count > 0]
547
581
 
548
- h_idx, = is_hydrogen.nonzero(as_tuple = True)
549
- heavy_idx, = (~is_hydrogen).nonzero(as_tuple = True)
582
+ if len(active) == 1:
583
+ return self.experts[active[0]](x)
550
584
 
551
- out = x.new_zeros((*x.shape[:-1], self.dim_out))
552
- out = out.index_copy(0, h_idx, self.hydrogen_expert(x[h_idx]))
553
- out = out.index_copy(0, heavy_idx, self.heavy_expert(x[heavy_idx]))
554
- return out
585
+ order = expert_ids_flat.argsort(stable = True)
586
+ chunks = x_flat[order].split(counts, dim = 0)
587
+ out_sorted = cat([expert(chunk) for expert, chunk, count in zip(self.experts, chunks, counts) if count > 0], dim = 0)
588
+
589
+ inv_order = torch.empty_like(order)
590
+ inv_order[order] = arange(order.numel(), device = order.device)
591
+ return inverse_pack(out_sorted[inv_order])
555
592
 
556
593
  class EGNNLayer(Module):
557
594
  def __init__(
@@ -566,13 +603,15 @@ class EGNNLayer(Module):
566
603
  edge_taper_exponent = 2,
567
604
  message_scale = 1e-2,
568
605
  vector_coeff_bound = 0.5,
569
- use_moe = True
606
+ num_experts = 1
570
607
  ):
571
608
  super().__init__()
609
+ assert num_experts >= 1, 'num_experts must be at least 1'
610
+
572
611
  self.cutoff = cutoff
573
612
  self.message_scale = message_scale
574
613
  self.vector_coeff_bound = vector_coeff_bound
575
- self.use_moe = use_moe
614
+ self.num_experts = num_experts
576
615
 
577
616
  self.radial_basis = FourierRadialBasis(
578
617
  num_radial_basis,
@@ -591,8 +630,11 @@ class EGNNLayer(Module):
591
630
  self.to_center_node = Linear(dim_node, dim_interaction, bias = False)
592
631
  self.to_neighbor_node = Linear(dim_node, dim_interaction)
593
632
 
594
- mlp_cls = TwoExpertMLP if use_moe else MLP
595
- self.message_mlp = mlp_cls(dim_interaction, *mlp_rest_dims, dim_node, activation = GELU())
633
+ self.message_mlp = (
634
+ MLP(dim_interaction, *mlp_rest_dims, dim_node, activation = GELU())
635
+ if num_experts == 1 else
636
+ MoEMLP(dim_interaction, *mlp_rest_dims, dim_node, num_experts = num_experts, activation = GELU())
637
+ )
596
638
 
597
639
  def forward(
598
640
  self,
@@ -603,7 +645,7 @@ class EGNNLayer(Module):
603
645
  edge_index: Tensor,
604
646
  edge_disp: Tensor,
605
647
  edge_dist: Tensor,
606
- is_hydrogen: Tensor | None = None
648
+ expert_ids: Tensor | None = None
607
649
  ):
608
650
  if edge_index.numel() == 0:
609
651
  return scalar_feats, vector_feats, virtual_charges
@@ -630,7 +672,7 @@ class EGNNLayer(Module):
630
672
  nuclear_virtual_basis = rearrange(self.radial_basis(nuclear_virtual_dist), 'e c f -> e (c f)')
631
673
  rel_virtual_virtual_dist = rearrange(rel_virtual_virtual_dist, 'e c1 c2 -> e (c1 c2)')
632
674
 
633
- # interaction space and H/heavy-atom MoE message mlp (eq. S4)
675
+ # interaction space and species-routed MoE message mlp (eq. S4)
634
676
 
635
677
  node_feats, node_packed_shape = pack([scalar_feats, core_charges, virtual_charges], 'n *')
636
678
 
@@ -645,9 +687,9 @@ class EGNNLayer(Module):
645
687
  + neighbor_proj[src]
646
688
  )
647
689
 
648
- if self.use_moe:
649
- edge_is_hydrogen = is_hydrogen[dst] if exists(is_hydrogen) else None
650
- messages = self.message_mlp(interaction, edge_is_hydrogen)
690
+ if self.num_experts > 1:
691
+ edge_expert_ids = expert_ids[dst] if exists(expert_ids) else None
692
+ messages = self.message_mlp(interaction, edge_expert_ids)
651
693
  else:
652
694
  messages = self.message_mlp(interaction)
653
695
 
@@ -685,18 +727,28 @@ class EGNNTrunk(Module):
685
727
  edge_taper_exponent = 2,
686
728
  message_scale = 1e-2,
687
729
  vector_coeff_bound = 0.5,
688
- use_moe = True,
689
- hydrogen_species_id: int | None = HYDROGEN_ATOMIC_NUM,
730
+ moe_atomic_nums: int | tuple[int | tuple[int, ...], ...] | None = (HYDROGEN_ATOMIC_NUM,),
690
731
  use_pyg: bool | None = None
691
732
  ):
692
733
  super().__init__()
693
734
  cutoffs = resolve_cutoffs(cutoffs, depth = depth)
735
+ moe_groups = resolve_moe_atomic_nums(moe_atomic_nums)
694
736
 
695
737
  self.depth = len(cutoffs)
696
738
  self.cutoffs = cutoffs
697
- self.hydrogen_species_id = hydrogen_species_id
739
+ self.moe_atomic_nums = moe_groups
740
+ self.num_experts = len(moe_groups) + 1
698
741
  self.use_pyg = use_pyg
699
742
 
743
+ pairs = sorted(
744
+ (z, expert_id)
745
+ for expert_id, group in enumerate(moe_groups, start = 1)
746
+ for z in group
747
+ )
748
+ keys, values = zip(*pairs) if pairs else ((), ())
749
+ self.register_buffer('moe_keys', tensor(keys, dtype = torch.long), persistent = False)
750
+ self.register_buffer('moe_values', tensor(values, dtype = torch.long), persistent = False)
751
+
700
752
  self.layers = ModuleList([
701
753
  EGNNLayer(
702
754
  dim = dim,
@@ -708,11 +760,19 @@ class EGNNTrunk(Module):
708
760
  edge_taper_exponent = edge_taper_exponent,
709
761
  message_scale = message_scale,
710
762
  vector_coeff_bound = vector_coeff_bound,
711
- use_moe = use_moe
763
+ num_experts = self.num_experts
712
764
  )
713
765
  for cutoff in cutoffs
714
766
  ])
715
767
 
768
+ def route_species(self, species: Tensor | None):
769
+ if self.num_experts == 1 or not exists(species):
770
+ return None
771
+
772
+ species_flat = rearrange(species, 'b n -> (b n)').to(self.moe_keys.dtype)
773
+ idx = torch.searchsorted(self.moe_keys, species_flat).clamp(max = self.moe_keys.numel() - 1)
774
+ return where(self.moe_keys[idx] == species_flat, self.moe_values[idx], 0)
775
+
716
776
  def forward(
717
777
  self,
718
778
  scalar_feats: Tensor,
@@ -732,11 +792,7 @@ class EGNNTrunk(Module):
732
792
  for t in (coords, scalar_feats, vector_feats, core_charges, virtual_charges)
733
793
  )
734
794
 
735
- is_hydrogen = (
736
- rearrange(species == self.hydrogen_species_id, 'b n -> (b n)')
737
- if exists(species) and exists(self.hydrogen_species_id)
738
- else None
739
- )
795
+ expert_ids = self.route_species(species)
740
796
 
741
797
  # build radius graph once at max cutoff and filter per unique layer cutoff
742
798
 
@@ -763,7 +819,7 @@ class EGNNTrunk(Module):
763
819
  core_flat,
764
820
  virtual_flat,
765
821
  *graph_cache[cutoff],
766
- is_hydrogen = is_hydrogen
822
+ expert_ids = expert_ids
767
823
  )
768
824
 
769
825
  return tuple(
@@ -787,8 +843,7 @@ class PENNe(Module):
787
843
  edge_taper_exponent = 2,
788
844
  message_scale = 1e-2,
789
845
  vector_coeff_bound = 0.5,
790
- use_moe = True,
791
- hydrogen_species_id: int | None = HYDROGEN_ATOMIC_NUM,
846
+ moe_atomic_nums: int | tuple[int | tuple[int, ...], ...] | None = (HYDROGEN_ATOMIC_NUM,),
792
847
  use_pyg: bool | None = None,
793
848
  trunk: Module | None = None,
794
849
  virtual_site_cap = 0.8,
@@ -850,8 +905,7 @@ class PENNe(Module):
850
905
  edge_taper_exponent = edge_taper_exponent,
851
906
  message_scale = message_scale,
852
907
  vector_coeff_bound = vector_coeff_bound,
853
- use_moe = use_moe,
854
- hydrogen_species_id = hydrogen_species_id,
908
+ moe_atomic_nums = moe_atomic_nums,
855
909
  use_pyg = use_pyg
856
910
  )
857
911
 
@@ -896,6 +950,10 @@ class PENNe(Module):
896
950
  def depth(self):
897
951
  return getattr(self.trunk, 'depth', None)
898
952
 
953
+ @property
954
+ def num_experts(self):
955
+ return getattr(self.trunk, 'num_experts', None)
956
+
899
957
  def forward(
900
958
  self,
901
959
  species: Tensor,
@@ -2,6 +2,6 @@ from PENNe_pytorch.PENNe import (
2
2
  PENNe,
3
3
  EGNNTrunk,
4
4
  EGNNLayer,
5
- TwoExpertMLP,
5
+ MoEMLP,
6
6
  build_radius_graph
7
7
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: PENNe-pytorch
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Summary: PENNe - PyTorch
5
5
  Project-URL: Homepage, https://pypi.org/project/PENNe-pytorch/
6
6
  Project-URL: Repository, https://github.com/lucidrains/PENNe-pytorch
@@ -74,6 +74,7 @@ model = PENNe(
74
74
  num_virtual_sites = 4,
75
75
  num_radial_basis = 16,
76
76
  mlp_hidden_dims = (256, 128),
77
+ moe_atomic_nums = (1,), # atomic numbers / groups for MoE experts (+ default heavy expert); None or () for non-MoE
77
78
  sigma_pol = 6.0, # polarization switching distance in angstroms
78
79
  dispersion_softening = 6.0 # dispersion softening radius in angstroms
79
80
  )
@@ -24,6 +24,7 @@ model = PENNe(
24
24
  num_virtual_sites = 4,
25
25
  num_radial_basis = 16,
26
26
  mlp_hidden_dims = (256, 128),
27
+ moe_atomic_nums = (1,), # atomic numbers / groups for MoE experts (+ default heavy expert); None or () for non-MoE
27
28
  sigma_pol = 6.0, # polarization switching distance in angstroms
28
29
  dispersion_softening = 6.0 # dispersion softening radius in angstroms
29
30
  )
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "PENNe-pytorch"
3
- version = "0.0.2"
3
+ version = "0.0.3"
4
4
  description = "PENNe - PyTorch"
5
5
  authors = [
6
6
  { name = "Phil Wang", email = "lucidrains@gmail.com" }
File without changes
File without changes