|
| 1 | +// Copyright 2026 gorse Project Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package main |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "log" |
| 21 | + "os" |
| 22 | + "runtime" |
| 23 | + "sort" |
| 24 | + |
| 25 | + "github.com/gorse-io/gorse/config" |
| 26 | + "github.com/gorse-io/gorse/dataset" |
| 27 | + "github.com/gorse-io/gorse/master" |
| 28 | + "github.com/gorse-io/gorse/model/ctr" |
| 29 | + "github.com/gorse-io/gorse/storage" |
| 30 | + "github.com/gorse-io/gorse/storage/data" |
| 31 | + "github.com/samber/lo" |
| 32 | + "github.com/spf13/cobra" |
| 33 | + "modernc.org/sortutil" |
| 34 | +) |
| 35 | + |
| 36 | +var rootCmd = &cobra.Command{ |
| 37 | + Use: "gorse-benchmark", |
| 38 | + Short: "Gorse Benchmarking Tool", |
| 39 | +} |
| 40 | + |
| 41 | +var llmCmd = &cobra.Command{ |
| 42 | + Use: "llm", |
| 43 | + Short: "Benchmark LLM models", |
| 44 | + Run: func(cmd *cobra.Command, args []string) { |
| 45 | + // Load configuration |
| 46 | + configPath, _ := cmd.Flags().GetString("config") |
| 47 | + cfg, err := config.LoadConfig(configPath) |
| 48 | + if err != nil { |
| 49 | + log.Fatalf("failed to load config: %v", err) |
| 50 | + } |
| 51 | + // Load dataset |
| 52 | + m := master.NewMaster(cfg, os.TempDir(), false) |
| 53 | + m.DataClient, err = data.Open(m.Config.Database.DataStore, m.Config.Database.DataTablePrefix, |
| 54 | + storage.WithIsolationLevel(m.Config.Database.MySQL.IsolationLevel)) |
| 55 | + if err != nil { |
| 56 | + log.Fatalf("failed to open data client: %v", err) |
| 57 | + } |
| 58 | + evaluator := master.NewOnlineEvaluator( |
| 59 | + m.Config.Recommend.DataSource.PositiveFeedbackTypes, |
| 60 | + m.Config.Recommend.DataSource.ReadFeedbackTypes) |
| 61 | + dataset, _, err := m.LoadDataFromDatabase(context.Background(), m.DataClient, |
| 62 | + m.Config.Recommend.DataSource.PositiveFeedbackTypes, |
| 63 | + m.Config.Recommend.DataSource.ReadFeedbackTypes, |
| 64 | + m.Config.Recommend.DataSource.ItemTTL, |
| 65 | + m.Config.Recommend.DataSource.PositiveFeedbackTTL, |
| 66 | + evaluator, |
| 67 | + nil) |
| 68 | + if err != nil { |
| 69 | + log.Fatalf("failed to load dataset: %v", err) |
| 70 | + } |
| 71 | + fmt.Println("Dataset loaded:") |
| 72 | + fmt.Printf(" Users: %d\n", dataset.CountUsers()) |
| 73 | + fmt.Printf(" Items: %d\n", dataset.CountItems()) |
| 74 | + fmt.Printf(" Positive Feedbacks: %d\n", dataset.CountPositive()) |
| 75 | + fmt.Printf(" Negative Feedbacks: %d\n", dataset.CountNegative()) |
| 76 | + // Split dataset |
| 77 | + train, test := dataset.Split(0.2, 42) |
| 78 | + EvaluateFM(train, test) |
| 79 | + // EvaluateLLM(cfg, train, test, aux.GetItems()) |
| 80 | + }, |
| 81 | +} |
| 82 | + |
| 83 | +func EvaluateFM(train, test dataset.CTRSplit) float32 { |
| 84 | + fmt.Println("Training FM...") |
| 85 | + ml := ctr.NewAFM(nil) |
| 86 | + ml.Fit(context.Background(), train, test, |
| 87 | + ctr.NewFitConfig(). |
| 88 | + SetVerbose(10). |
| 89 | + SetJobs(runtime.NumCPU()). |
| 90 | + SetPatience(10)) |
| 91 | + |
| 92 | + userTrain := make(map[int32]int, train.CountUsers()) |
| 93 | + for i := 0; i < train.Count(); i++ { |
| 94 | + indices, _, _, target := train.Get(i) |
| 95 | + userId := indices[0] |
| 96 | + if target > 0 { |
| 97 | + userTrain[userId]++ |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + var posFeatures, negFeatures []lo.Tuple2[[]int32, []float32] |
| 102 | + var posEmbeddings, negEmbeddings [][][]float32 |
| 103 | + var posUsers, negUsers []int32 |
| 104 | + for i := 0; i < test.Count(); i++ { |
| 105 | + indices, values, embeddings, target := test.Get(i) |
| 106 | + userId := indices[0] |
| 107 | + if target > 0 { |
| 108 | + posFeatures = append(posFeatures, lo.Tuple2[[]int32, []float32]{A: indices, B: values}) |
| 109 | + posEmbeddings = append(posEmbeddings, embeddings) |
| 110 | + posUsers = append(posUsers, userId) |
| 111 | + } else { |
| 112 | + negFeatures = append(negFeatures, lo.Tuple2[[]int32, []float32]{A: indices, B: values}) |
| 113 | + negEmbeddings = append(negEmbeddings, embeddings) |
| 114 | + negUsers = append(negUsers, userId) |
| 115 | + } |
| 116 | + } |
| 117 | + posPrediction := ml.BatchInternalPredict(posFeatures, posEmbeddings, runtime.NumCPU()) |
| 118 | + negPrediction := ml.BatchInternalPredict(negFeatures, negEmbeddings, runtime.NumCPU()) |
| 119 | + |
| 120 | + userPosPrediction := make(map[int32][]float32) |
| 121 | + userNegPrediction := make(map[int32][]float32) |
| 122 | + for i, p := range posPrediction { |
| 123 | + userPosPrediction[posUsers[i]] = append(userPosPrediction[posUsers[i]], p) |
| 124 | + } |
| 125 | + for i, p := range negPrediction { |
| 126 | + userNegPrediction[negUsers[i]] = append(userNegPrediction[negUsers[i]], p) |
| 127 | + } |
| 128 | + var sumAUC float32 |
| 129 | + var validUsers float32 |
| 130 | + for user, pos := range userPosPrediction { |
| 131 | + if userTrain[user] > 100 || userTrain[user] == 0 { |
| 132 | + continue |
| 133 | + } |
| 134 | + if neg, ok := userNegPrediction[user]; ok { |
| 135 | + sumAUC += AUC(pos, neg) * float32(len(pos)) |
| 136 | + validUsers += float32(len(pos)) |
| 137 | + } |
| 138 | + } |
| 139 | + if validUsers == 0 { |
| 140 | + return 0 |
| 141 | + } |
| 142 | + score := sumAUC / validUsers |
| 143 | + |
| 144 | + fmt.Println("FM GAUC:", score) |
| 145 | + return score |
| 146 | +} |
| 147 | + |
| 148 | +func AUC(posPrediction, negPrediction []float32) float32 { |
| 149 | + sort.Sort(sortutil.Float32Slice(posPrediction)) |
| 150 | + sort.Sort(sortutil.Float32Slice(negPrediction)) |
| 151 | + var sum float32 |
| 152 | + var nPos int |
| 153 | + for pPos := range posPrediction { |
| 154 | + // find the negative sample with the greatest prediction less than current positive sample |
| 155 | + for nPos < len(negPrediction) && negPrediction[nPos] < posPrediction[pPos] { |
| 156 | + nPos++ |
| 157 | + } |
| 158 | + // add the number of negative samples have less prediction than current positive sample |
| 159 | + sum += float32(nPos) |
| 160 | + } |
| 161 | + if len(posPrediction)*len(negPrediction) == 0 { |
| 162 | + return 0 |
| 163 | + } |
| 164 | + return sum / float32(len(posPrediction)*len(negPrediction)) |
| 165 | +} |
| 166 | + |
| 167 | +func init() { |
| 168 | + rootCmd.PersistentFlags().StringP("config", "c", "", "Path to configuration file") |
| 169 | + rootCmd.AddCommand(llmCmd) |
| 170 | +} |
| 171 | + |
| 172 | +func main() { |
| 173 | + if err := rootCmd.Execute(); err != nil { |
| 174 | + log.Fatal(err) |
| 175 | + } |
| 176 | +} |
0 commit comments