gobrec 0.1.0__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.
gobrec-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 RecSys-UFSCar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
gobrec-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.1
2
+ Name: gobrec
3
+ Version: 0.1.0
4
+ Description-Content-Type: text/markdown
5
+ License-File: LICENSE
6
+
7
+ # gobrec
8
+ GOBRec: GPU Optimized Bandits Recommender
gobrec-0.1.0/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # gobrec
2
+ GOBRec: GPU Optimized Bandits Recommender
@@ -0,0 +1,29 @@
1
+
2
+ from gobrec.mabs.lin_mabs.Lin import Lin
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ class Recommender:
8
+
9
+ def __init__(self, mab_algo: Lin, top_k: int):
10
+ self.mab_algo = mab_algo
11
+ self.top_k = top_k
12
+
13
+ def fit(self, contexts: np.ndarray, items_ids: np.ndarray, rewards: np.ndarray):
14
+ self.mab_algo.fit(contexts, items_ids, rewards)
15
+
16
+ def recommend(self, contexts: np.ndarray, items_ids_filter: 'list[np.ndarray, np.ndarray]' = None):
17
+ # ITEMS IDS FILTERS is a tuple where the first element is a list of indices (of contexts) to filter and the second element is the items_ids to filter
18
+
19
+ expectations = self.mab_algo.predict(contexts)
20
+
21
+ if items_ids_filter is not None:
22
+ items_ids_filter[1] = self.mab_algo.label_encoder.transform(items_ids_filter[1])
23
+ expectations[items_ids_filter] = -100.
24
+
25
+ topk_sorted_expectations = torch.topk(expectations, self.top_k, dim=1)
26
+ recommendations = self.mab_algo.label_encoder.inverse_transform(topk_sorted_expectations.indices.cpu().numpy().flatten()).reshape(contexts.shape[0], self.top_k)
27
+ scores = topk_sorted_expectations.values.cpu().numpy()
28
+
29
+ return recommendations, scores
@@ -0,0 +1,2 @@
1
+
2
+ from gobrec.Recommender import Recommender
@@ -0,0 +1,52 @@
1
+
2
+ from abc import ABC, abstractmethod
3
+ import numpy as np
4
+ from sklearn.preprocessing import LabelEncoder
5
+
6
+
7
+ class MABAlgo(ABC):
8
+ """
9
+ Abstract class for Multi-Armed Bandit algorithms.
10
+ """
11
+
12
+ def __init__(self, seed: int = None):
13
+ self.seed = seed
14
+ self.rng = np.random.default_rng(self.seed)
15
+ self.label_encoder = None
16
+ self.num_arms = None
17
+ self.num_features = None
18
+
19
+ def _update_label_encoder(self, items_ids: np.ndarray, num_features: int):
20
+ """
21
+ Update the label encoder with new item IDs.
22
+ """
23
+ if self.label_encoder is None:
24
+ self.label_encoder = LabelEncoder()
25
+ self.label_encoder.fit(items_ids)
26
+ self.num_arms = len(self.label_encoder.classes_)
27
+ else:
28
+ new_classes = np.setdiff1d(items_ids, self.label_encoder.classes_)
29
+ if len(new_classes) > 0:
30
+ all_classes = np.concatenate((self.label_encoder.classes_, new_classes))
31
+ self.label_encoder.fit(all_classes)
32
+ self.num_arms = len(self.label_encoder.classes_)
33
+
34
+ if self.num_features is None:
35
+ self.num_features = num_features
36
+
37
+ assert num_features == self.num_features, "Number of features has changed!"
38
+
39
+
40
+ @abstractmethod
41
+ def fit(self, contexts: np.ndarray, items_ids: np.ndarray, rewards: np.ndarray):
42
+ """
43
+ Fit the MAB algorithm with the provided contexts, item IDs, and rewards.
44
+ """
45
+ pass
46
+
47
+ @abstractmethod
48
+ def predict(self, contexts: np.ndarray) -> np.ndarray:
49
+ """
50
+ Predict the expected rewards for the given contexts.
51
+ """
52
+ pass
File without changes
@@ -0,0 +1,67 @@
1
+
2
+ import torch
3
+ import numpy as np
4
+ from sklearn.preprocessing import LabelEncoder
5
+ from gobrec.mabs.MABAlgo import MABAlgo
6
+
7
+
8
+ class Lin(MABAlgo):
9
+
10
+ def __init__(self, seed: int = None, l2_lambda: float = 1.0, use_gpu: bool = False, items_per_batch: int = 10_000):
11
+
12
+ super().__init__(seed)
13
+
14
+ self.l2_lambda = l2_lambda
15
+ self.device = 'cuda' if use_gpu else 'cpu'
16
+
17
+ self.items_per_batch = items_per_batch
18
+ self.already_initialized = False
19
+
20
+ def _update_label_encoder_and_matrices_sizes(self, items_ids: np.ndarray, num_features: int):
21
+
22
+ self._update_label_encoder(items_ids, num_features)
23
+
24
+ if not self.already_initialized:
25
+ self.Xty = torch.zeros((self.num_arms, self.num_features), device=self.device, dtype=torch.double)
26
+ self.A = torch.eye(self.num_features, device=self.device, dtype=torch.double).unsqueeze(0).repeat(self.num_arms, 1, 1) * self.l2_lambda
27
+ self.beta = torch.zeros((self.num_arms, self.num_features), device=self.device, dtype=torch.double)
28
+ elif self.num_arms != self.beta.shape[0]:
29
+ # the number of arms has changed, we need to update the matrices
30
+ Xty_new = torch.zeros((self.num_arms, self.num_features), device=self.device, dtype=torch.double)
31
+ Xty_new[:self.Xty.shape[0]] = self.Xty
32
+ self.Xty = Xty_new
33
+
34
+ A_new = torch.eye(self.num_features, device=self.device, dtype=torch.double).unsqueeze(0).repeat(self.num_arms, 1, 1) * self.l2_lambda
35
+ A_new[:self.A.shape[0]] = self.A
36
+ self.A = A_new
37
+
38
+ beta_new = torch.zeros((self.num_arms, self.num_features), device=self.device, dtype=torch.double)
39
+ beta_new[:self.beta.shape[0]] = self.beta
40
+ self.beta = beta_new
41
+
42
+
43
+ def fit(self, contexts: np.ndarray, items_ids: np.ndarray, rewards: np.ndarray):
44
+
45
+ self._update_label_encoder_and_matrices_sizes(items_ids, contexts.shape[1])
46
+
47
+ X_device = torch.tensor(contexts, device=self.device, dtype=torch.double)
48
+ y_device = torch.tensor(rewards, device=self.device, dtype=torch.double)
49
+ decisions_device = torch.tensor(self.label_encoder.transform(items_ids), device=self.device, dtype=torch.long)
50
+
51
+ self.A.index_add_(0, decisions_device, torch.einsum('ni,nj->nij', X_device, X_device))
52
+
53
+ self.Xty.index_add_(0, decisions_device, X_device * y_device.view(-1, 1))
54
+
55
+ for j in range(0, self.beta.shape[0], self.items_per_batch):
56
+ self.beta[j:j+self.items_per_batch] = torch.linalg.solve(
57
+ self.A[j:j+self.items_per_batch],
58
+ self.Xty[j:j+self.items_per_batch]
59
+ )
60
+
61
+ def predict(self, contexts: np.ndarray):
62
+ scores = torch.empty((contexts.shape[0], self.num_arms), device=self.device, dtype=torch.double)
63
+ for start in range(0, self.num_arms, self.items_per_batch):
64
+ end = min(start + self.items_per_batch, self.num_arms)
65
+ scores[:, start:end] = torch.einsum('bd,ad->ba', torch.tensor(contexts, device=self.device, dtype=torch.double), self.beta[start:end])
66
+
67
+ return scores
@@ -0,0 +1,31 @@
1
+
2
+ from gobrec.mabs.lin_mabs import Lin
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ class LinGreedy(Lin):
8
+
9
+ def __init__(self, seed: int = None, epsilon: float = 0.1, l2_lambda: float = 1.0, use_gpu: bool = False, items_per_batch: int = 10_000):
10
+
11
+ super().__init__(seed, l2_lambda, use_gpu, items_per_batch)
12
+ self.epsilon = epsilon
13
+
14
+
15
+ def predict(self, contexts: np.ndarray):
16
+
17
+ x = torch.tensor(contexts, device=self.device, dtype=torch.double)
18
+
19
+ scores = torch.empty((contexts.shape[0], self.num_arms), device=self.device, dtype=torch.double)
20
+ random_mask = self.rng.random(contexts.shape[0]) < self.epsilon
21
+ random_indexes = random_mask.nonzero()[0]
22
+ not_random_indexes = (~random_mask).nonzero()[0]
23
+
24
+ scores[random_mask] = torch.tensor(self.rng.random((len(random_indexes), self.num_arms)), device=self.device, dtype=torch.double)
25
+
26
+ for start in range(0, len(not_random_indexes), self.items_per_batch):
27
+ end = min(start + self.items_per_batch, len(not_random_indexes))
28
+ batch_indexes = not_random_indexes[start:end]
29
+ scores[batch_indexes] = torch.einsum('bd,ad->ba', x[batch_indexes], self.beta)
30
+
31
+ return scores
@@ -0,0 +1,35 @@
1
+
2
+ from gobrec.mabs.lin_mabs import Lin
3
+ import numpy as np
4
+ import torch
5
+
6
+ class LinTS(Lin):
7
+
8
+ def __init__(self, seed: int = None, alpha: float = 1.0, l2_lambda: float = 1.0, use_gpu: bool = False, items_per_batch: int = 10_000):
9
+
10
+ super().__init__(seed, l2_lambda, use_gpu, items_per_batch)
11
+ self.alpha = alpha
12
+
13
+ def predict(self, contexts: np.ndarray):
14
+ x = torch.tensor(contexts, device=self.device, dtype=torch.double)
15
+
16
+ num_arms, num_features = self.beta.shape
17
+ num_contexts = contexts.shape[0]
18
+
19
+ scores = torch.empty((num_contexts, num_arms), device=self.device, dtype=torch.double)
20
+
21
+ eps = torch.from_numpy(self.rng.standard_normal(size=(num_contexts, num_features))).to(device=self.device, dtype=torch.double)
22
+
23
+ for start in range(0, num_arms, self.items_per_batch):
24
+ end = min(start + self.items_per_batch, num_arms)
25
+
26
+ beta_chunk = self.beta[start:end]
27
+ A_chunk = self.A[start:end]
28
+ A_inv_chunk = torch.linalg.inv(A_chunk)
29
+
30
+ L_chunk = torch.linalg.cholesky((self.alpha ** 2) * A_inv_chunk)
31
+ beta_sampled = torch.einsum('bd,add->bad', eps, L_chunk) + beta_chunk
32
+
33
+ scores[:, start:end] = torch.einsum('bd,bad->ba', x, beta_sampled)
34
+
35
+ return scores
@@ -0,0 +1,31 @@
1
+
2
+ from gobrec.mabs.lin_mabs import Lin
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ class LinUCB(Lin):
8
+
9
+ def __init__(self, seed: int = None, alpha: float = 1.0, l2_lambda: float = 1.0, use_gpu: bool = False, items_per_batch: int = 10_000):
10
+
11
+ super().__init__(seed, l2_lambda, use_gpu, items_per_batch)
12
+ self.alpha = alpha
13
+
14
+
15
+ def predict(self, contexts: np.ndarray):
16
+
17
+ x = torch.tensor(contexts, device=self.device, dtype=torch.double)
18
+
19
+ scores = torch.matmul(x, self.beta.T)
20
+
21
+ for j in range(0, self.beta.shape[0], self.items_per_batch):
22
+ x_A_inv = torch.matmul(x, torch.linalg.inv(self.A[j: j+self.items_per_batch]))
23
+
24
+ # Upper confidence bound = alpha * sqrt(x A^-1 xt). Notice that, x = xt
25
+ # ucb values are claculated for all the contexts in one single go. type(ucb): np.ndarray
26
+ ucb = self.alpha * torch.sqrt(torch.sum(x_A_inv * x, axis=2))
27
+
28
+ # Calculate linucb expectation y = x * b + ucb
29
+ scores[:, j: j+self.items_per_batch] += ucb.T
30
+
31
+ return scores
@@ -0,0 +1,5 @@
1
+
2
+ from gobrec.mabs.lin_mabs.Lin import Lin
3
+ from gobrec.mabs.lin_mabs.LinUCB import LinUCB
4
+ from gobrec.mabs.lin_mabs.LinGreedy import LinGreedy
5
+ from gobrec.mabs.lin_mabs.LinTS import LinTS
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.1
2
+ Name: gobrec
3
+ Version: 0.1.0
4
+ Description-Content-Type: text/markdown
5
+ License-File: LICENSE
6
+
7
+ # gobrec
8
+ GOBRec: GPU Optimized Bandits Recommender
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ gobrec/Recommender.py
5
+ gobrec/__init__.py
6
+ gobrec.egg-info/PKG-INFO
7
+ gobrec.egg-info/SOURCES.txt
8
+ gobrec.egg-info/dependency_links.txt
9
+ gobrec.egg-info/requires.txt
10
+ gobrec.egg-info/top_level.txt
11
+ gobrec/mabs/MABAlgo.py
12
+ gobrec/mabs/__init__.py
13
+ gobrec/mabs/lin_mabs/Lin.py
14
+ gobrec/mabs/lin_mabs/LinGreedy.py
15
+ gobrec/mabs/lin_mabs/LinTS.py
16
+ gobrec/mabs/lin_mabs/LinUCB.py
17
+ gobrec/mabs/lin_mabs/__init__.py
@@ -0,0 +1,3 @@
1
+ torch
2
+ numpy
3
+ scikit-learn
@@ -0,0 +1 @@
1
+ gobrec
gobrec-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
gobrec-0.1.0/setup.py ADDED
@@ -0,0 +1,18 @@
1
+
2
+ from setuptools import setup, find_packages
3
+
4
+ with open('README.md', 'r') as f:
5
+ description = f.read()
6
+
7
+ setup(
8
+ name='gobrec',
9
+ version='0.1.0',
10
+ packages=find_packages(),
11
+ install_requires=[
12
+ 'torch',
13
+ 'numpy',
14
+ 'scikit-learn'
15
+ ],
16
+ long_description=description,
17
+ long_description_content_type='text/markdown'
18
+ )