├── src ├── __init__.py └── DIN.py ├── img └── submit_v1.png ├── data ├── README.md └── prepare_data_v1.py ├── fuxictr_version.py ├── requirements.txt ├── config ├── base_config │ ├── dataset_config.yaml │ └── model_config.yaml └── DIN_ebnerd_large_x1_tuner_config_01.yaml ├── run_param_tuner.py ├── .gitignore ├── run_expid.py ├── submit.py ├── README.md └── LICENSE /src/__init__.py: -------------------------------------------------------------------------------- 1 | from .DIN import * 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /img/submit_v1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reczoo/RecSys2024_CTR_Challenge/HEAD/img/submit_v1.png -------------------------------------------------------------------------------- /data/README.md: -------------------------------------------------------------------------------- 1 | # Dataset 2 | 3 | Directories: 4 | + Ebnerd: raw data 5 | + Ebnerd_large_x1: preprocessed csv data 6 | + ebnerd_large_x1_xxxxxxxx: preprocessed npz data 7 | -------------------------------------------------------------------------------- /fuxictr_version.py: -------------------------------------------------------------------------------- 1 | """ 2 | Please install fuxictr first, or directly add the package to sys.path 3 | """ 4 | import fuxictr 5 | assert fuxictr.__version__ == "2.2.3" 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | fuxictr==2.2.3 2 | keras_preprocessing 3 | PyYAML 4 | pandas 5 | scikit-learn 6 | numpy 7 | h5py 8 | tqdm 9 | pyarrow 10 | polars<1.0.0 11 | -------------------------------------------------------------------------------- /config/base_config/dataset_config.yaml: -------------------------------------------------------------------------------- 1 | ### Tiny data for tests only 2 | tiny_seq: 3 | data_root: ../../data/ 4 | data_format: npz 5 | train_data: ../../data/tiny_seq/train.npz 6 | valid_data: ../../data/tiny_seq/valid.npz 7 | test_data: ../../data/tiny_seq/test.npz 8 | 9 | 10 | -------------------------------------------------------------------------------- /run_param_tuner.py: -------------------------------------------------------------------------------- 1 | # ========================================================================= 2 | # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ========================================================================= 16 | 17 | from datetime import datetime 18 | import gc 19 | import argparse 20 | import fuxictr_version 21 | from fuxictr import autotuner 22 | 23 | if __name__ == '__main__': 24 | parser = argparse.ArgumentParser() 25 | parser.add_argument('--config', type=str, default='../config/tuner_config.yaml', 26 | help='The config file for para tuning.') 27 | parser.add_argument('--tag', type=str, default=None, help='Use the tag to determine which expid to run (e.g. 001 for the first expid).') 28 | parser.add_argument('--gpu', nargs='+', default=[-1], help='The list of gpu indexes, -1 for cpu.') 29 | args = vars(parser.parse_args()) 30 | gpu_list = args['gpu'] 31 | expid_tag = args['tag'] 32 | 33 | # generate parameter space combinations 34 | config_dir = autotuner.enumerate_params(args['config']) 35 | autotuner.grid_search(config_dir, gpu_list, expid_tag) 36 | 37 | -------------------------------------------------------------------------------- /config/base_config/model_config.yaml: -------------------------------------------------------------------------------- 1 | Base: 2 | model_root: './checkpoints/' 3 | num_workers: 3 4 | verbose: 1 5 | early_stop_patience: 2 6 | pickle_feature_encoder: True 7 | save_best_only: True 8 | eval_steps: null 9 | debug_mode: False 10 | group_id: null 11 | use_features: null 12 | feature_specs: null 13 | feature_config: null 14 | 15 | DIN_test: 16 | model: DIN 17 | dataset_id: tiny_seq 18 | loss: 'binary_crossentropy' 19 | metrics: ['logloss', 'AUC'] 20 | task: binary_classification 21 | optimizer: adam 22 | learning_rate: 1.0e-3 23 | embedding_regularizer: 0 24 | net_regularizer: 0 25 | batch_size: 128 26 | embedding_dim: 4 27 | dnn_hidden_units: [64, 32] 28 | dnn_activations: relu 29 | attention_hidden_units: [64] 30 | attention_hidden_activations: "Dice" 31 | attention_output_activation: null 32 | attention_dropout: 0 33 | din_target_field: adgroup_id 34 | din_sequence_field: click_sequence 35 | net_dropout: 0 36 | batch_norm: False 37 | epochs: 1 38 | shuffle: True 39 | seed: 2019 40 | monitor: 'AUC' 41 | monitor_mode: 'max' 42 | 43 | DIN_test2: 44 | model: DIN 45 | dataset_id: tiny_seq2 46 | loss: 'binary_crossentropy' 47 | metrics: ['logloss', 'AUC'] 48 | task: binary_classification 49 | optimizer: adam 50 | learning_rate: 1.0e-3 51 | embedding_regularizer: 0 52 | net_regularizer: 0 53 | batch_size: 128 54 | embedding_dim: 4 55 | dnn_hidden_units: [64, 32] 56 | dnn_activations: relu 57 | attention_hidden_units: [64] 58 | attention_hidden_activations: "Dice" 59 | attention_output_activation: null 60 | attention_dropout: 0 61 | din_target_field: adgroup_id 62 | din_sequence_field: click_sequence 63 | net_dropout: 0 64 | batch_norm: False 65 | epochs: 1 66 | shuffle: True 67 | seed: 2019 68 | monitor: 'AUC' 69 | monitor_mode: 'max' 70 | 71 | DIN_default: # This is a config template 72 | model: DIN 73 | dataset_id: TBD 74 | loss: 'binary_crossentropy' 75 | metrics: ['logloss', 'AUC'] 76 | task: binary_classification 77 | optimizer: adam 78 | learning_rate: 1.0e-3 79 | embedding_regularizer: 0 80 | net_regularizer: 0 81 | batch_size: 10000 82 | embedding_dim: 40 83 | dnn_hidden_units: [500, 500, 500] 84 | dnn_activations: relu 85 | attention_hidden_units: [64] 86 | attention_hidden_activations: "Dice" 87 | attention_output_activation: null 88 | attention_dropout: 0 89 | din_target_field: item_id 90 | din_sequence_field: click_history 91 | din_use_softmax: False 92 | net_dropout: 0 93 | batch_norm: False 94 | epochs: 100 95 | shuffle: True 96 | seed: 2019 97 | monitor: {'AUC': 1, 'logloss': -1} 98 | monitor_mode: 'max' 99 | 100 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # ignore dataset 86 | Ebnerd_* 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # poetry 101 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 102 | # This is especially recommended for binary packages to ensure reproducibility, and is more 103 | # commonly ignored for libraries. 104 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 105 | #poetry.lock 106 | 107 | # pdm 108 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 109 | #pdm.lock 110 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 111 | # in version control. 112 | # https://pdm.fming.dev/#use-with-ide 113 | .pdm.toml 114 | 115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 116 | __pypackages__/ 117 | 118 | # Celery stuff 119 | celerybeat-schedule 120 | celerybeat.pid 121 | 122 | # SageMath parsed files 123 | *.sage.py 124 | 125 | # Environments 126 | .env 127 | .venv 128 | env/ 129 | venv/ 130 | ENV/ 131 | env.bak/ 132 | venv.bak/ 133 | 134 | # Spyder project settings 135 | .spyderproject 136 | .spyproject 137 | 138 | # Rope project settings 139 | .ropeproject 140 | 141 | # mkdocs documentation 142 | /site 143 | 144 | # mypy 145 | .mypy_cache/ 146 | .dmypy.json 147 | dmypy.json 148 | 149 | # Pyre type checker 150 | .pyre/ 151 | 152 | # pytype static type analyzer 153 | .pytype/ 154 | 155 | # Cython debug symbols 156 | cython_debug/ 157 | 158 | # PyCharm 159 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 160 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 161 | # and can be added to the global gitignore or merged into this file. For a more nuclear 162 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 163 | #.idea/ 164 | -------------------------------------------------------------------------------- /run_expid.py: -------------------------------------------------------------------------------- 1 | # ========================================================================= 2 | # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ========================================================================= 16 | 17 | 18 | import os 19 | os.chdir(os.path.dirname(os.path.realpath(__file__))) 20 | import sys 21 | import logging 22 | import fuxictr_version 23 | from fuxictr import datasets 24 | from datetime import datetime 25 | from fuxictr.utils import load_config, set_logger, print_to_json, print_to_list 26 | from fuxictr.features import FeatureMap 27 | from fuxictr.pytorch.dataloaders import RankDataLoader 28 | from fuxictr.pytorch.torch_utils import seed_everything 29 | from fuxictr.preprocess import FeatureProcessor, build_dataset 30 | import src 31 | import gc 32 | import argparse 33 | import os 34 | from pathlib import Path 35 | 36 | 37 | if __name__ == '__main__': 38 | ''' Usage: python run_expid.py --config {config_dir} --expid {experiment_id} --gpu {gpu_device_id} 39 | ''' 40 | parser = argparse.ArgumentParser() 41 | parser.add_argument('--config', type=str, default='./config/', help='The config directory.') 42 | parser.add_argument('--expid', type=str, default='DeepFM_test', help='The experiment id to run.') 43 | parser.add_argument('--gpu', type=int, default=-1, help='The gpu index, -1 for cpu') 44 | args = vars(parser.parse_args()) 45 | 46 | experiment_id = args['expid'] 47 | params = load_config(args['config'], experiment_id) 48 | params['gpu'] = args['gpu'] 49 | set_logger(params) 50 | logging.info("Params: " + print_to_json(params)) 51 | seed_everything(seed=params['seed']) 52 | 53 | data_dir = os.path.join(params['data_root'], params['dataset_id']) 54 | feature_map_json = os.path.join(data_dir, "feature_map.json") 55 | if params["data_format"] == "csv": 56 | # Build feature_map and transform data 57 | feature_encoder = FeatureProcessor(**params) 58 | params["train_data"], params["valid_data"], params["test_data"] = \ 59 | build_dataset(feature_encoder, **params) 60 | feature_map = FeatureMap(params['dataset_id'], data_dir) 61 | feature_map.load(feature_map_json, params) 62 | logging.info("Feature specs: " + print_to_json(feature_map.features)) 63 | 64 | model_class = getattr(src, params['model']) 65 | model = model_class(feature_map, **params) 66 | model.count_parameters() # print number of parameters used in model 67 | 68 | train_gen, valid_gen = RankDataLoader(feature_map, stage='train', **params).make_iterator() 69 | model.fit(train_gen, validation_data=valid_gen, **params) 70 | 71 | logging.info('****** Validation evaluation ******') 72 | valid_result = model.evaluate(valid_gen) 73 | del train_gen, valid_gen 74 | gc.collect() 75 | 76 | test_result = {} 77 | result_filename = Path(args['config']).name.replace(".yaml", "") + '.csv' 78 | with open(result_filename, 'a+') as fw: 79 | fw.write(' {},[command] python {},[exp_id] {},[dataset_id] {},[train] {},[val] {},[test] {}\n' \ 80 | .format(datetime.now().strftime('%Y%m%d-%H%M%S'), 81 | ' '.join(sys.argv), experiment_id, params['dataset_id'], 82 | "N.A.", print_to_list(valid_result), print_to_list(test_result))) 83 | -------------------------------------------------------------------------------- /submit.py: -------------------------------------------------------------------------------- 1 | # ========================================================================= 2 | # Copyright (C) 2024. FuxiCTR Authors. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ========================================================================= 16 | 17 | import os 18 | os.chdir(os.path.dirname(os.path.realpath(__file__))) 19 | import sys 20 | import logging 21 | import fuxictr_version 22 | from fuxictr import datasets 23 | from datetime import datetime 24 | from fuxictr.utils import load_config, set_logger, print_to_json, print_to_list 25 | from fuxictr.features import FeatureMap 26 | from fuxictr.pytorch.dataloaders import RankDataLoader 27 | from fuxictr.pytorch.torch_utils import seed_everything 28 | from fuxictr.preprocess import FeatureProcessor, build_dataset 29 | import src 30 | import gc 31 | import argparse 32 | import os 33 | from pathlib import Path 34 | import polars as pl 35 | import shutil 36 | import multiprocessing as mp 37 | import pandas as pd 38 | 39 | 40 | def grank(x): 41 | scores = x["score"].tolist() 42 | tmp = [(i, s) for i, s in enumerate(scores)] 43 | tmp = sorted(tmp, key=lambda y: y[-1], reverse=True) 44 | rank = [(i+1, t[0]) for i, t in enumerate(tmp)] 45 | rank = [str(r[0]) for r in sorted(rank, key=lambda y: y[-1])] 46 | rank = "[" + ",".join(rank) + "]" 47 | return str(x["impression_id"].iloc[0]) + " " + rank 48 | 49 | if __name__ == '__main__': 50 | ''' Usage: python run_expid.py --config {config_dir} --expid {experiment_id} --gpu {gpu_device_id} 51 | ''' 52 | parser = argparse.ArgumentParser() 53 | parser.add_argument('--config', type=str, default='./config/', help='The config directory.') 54 | parser.add_argument('--expid', type=str, default='DeepFM_test', help='The experiment id to run.') 55 | parser.add_argument('--gpu', type=int, default=-1, help='The gpu index, -1 for cpu') 56 | args = vars(parser.parse_args()) 57 | 58 | experiment_id = args['expid'] 59 | params = load_config(args['config'], experiment_id) 60 | params['gpu'] = args['gpu'] 61 | set_logger(params) 62 | logging.info("Params: " + print_to_json(params)) 63 | seed_everything(seed=params['seed']) 64 | 65 | data_dir = os.path.join(params['data_root'], params['dataset_id']) 66 | feature_map_json = os.path.join(data_dir, "feature_map.json") 67 | if params["data_format"] == "csv": 68 | # Build feature_map and transform data 69 | feature_encoder = FeatureProcessor(**params) 70 | params["train_data"], params["valid_data"], params["test_data"] = \ 71 | build_dataset(feature_encoder, **params) 72 | feature_map = FeatureMap(params['dataset_id'], data_dir) 73 | feature_map.load(feature_map_json, params) 74 | logging.info("Feature specs: " + print_to_json(feature_map.features)) 75 | 76 | model_class = getattr(src, params['model']) 77 | model = model_class(feature_map, **params) 78 | model.count_parameters() # print number of parameters used in model 79 | model.to(device=model.device) 80 | model.load_weights(model.checkpoint) 81 | 82 | params["batch_size"] = 16000 83 | test_gen = RankDataLoader(feature_map, stage='test', **params).make_iterator() 84 | ans = pl.scan_csv("./data/Ebnerd_large_x1/test.csv") 85 | ans = ans.select(['impression_id', 'user_id']).collect().to_pandas() 86 | logging.info("Predicting scores...") 87 | ans["score"] = model.predict(test_gen) 88 | logging.info("Ranking samples...") 89 | ans = ans.groupby(['impression_id', 'user_id'], sort=False).apply(grank).reset_index(drop=True) 90 | logging.info("Writing results...") 91 | os.makedirs("submit", exist_ok=True) 92 | with open('submit/predictions.txt', "w") as fout: 93 | fout.write("\n".join(ans.to_list())) 94 | shutil.make_archive(f'submit/{experiment_id}', 'zip', 'submit/', 'predictions.txt') 95 | logging.info("All done.") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## RecSys2024_CTR_Challenge 2 | 3 | The RecSys 2024 Challenge: https://www.recsyschallenge.com/2024/ 4 | 5 | The Ekstra Bladet RecSys Challenge aims to predict which article a user will click on from a list of articles that were seen during a specific impression. Utilizing the user's click history, session details (like time and device used), and personal metadata (including gender and age), along with a list of candidate news articles listed in an impression log, the challenge's objective is to rank the candidate articles based on the user's personal preferences. 6 | 7 | This baseline is built on top of [FuxiCTR](https://github.com/reczoo/FuxiCTR), a configurable, tunable, and reproducible library for CTR prediction. The library has been selected among [the list of recommended evaluation frameworks](https://github.com/ACMRecSys/recsys-evaluation-frameworks) by the ACM RecSys Conference. By using FuxiCTR, we develop a simple yet strong baseline (AUC: 0.7154) without heavy tuning. We open source the code to help beginers get familar with FuxiCTR and quickly get started on this task. 8 | 9 | 🔥 If you find our code helpful in your competition, please cite the following paper: 10 | 11 | + Jieming Zhu, Jinyang Liu, Shuai Yang, Qi Zhang, Xiuqiang He. [Open Benchmarking for Click-Through Rate Prediction](https://arxiv.org/abs/2009.05794). *The 30th ACM International Conference on Information and Knowledge Management (CIKM)*, 2021. 12 | 13 | 14 | ### Data Preparation 15 | 16 | Note that the dataset is quite large. Preparing the full dataset needs about 1T disk space. Although some optimizations can be made to save space (e.g., store sequence features sperately), we leave it for future exploration. 17 | 18 | 1. Download the datasets at: https://recsys.eb.dk/#dataset 19 | 20 | 2. Unzip the data files to the following 21 | 22 | ```bash 23 | cd ~/RecSys2024_CTR_Challenge/data/Ebnerd/ 24 | find -L . 25 | 26 | . 27 | ./train 28 | ./train/history.parquet 29 | ./train/articles.parquet 30 | ./train/behaviors.parquet 31 | ./validation 32 | ./validation/history.parquet 33 | ./validation/behaviors.parquet 34 | ./test 35 | ./test/history.parquet 36 | ./test/articles.parquet 37 | ./test/behaviors.parquet 38 | ./image_embeddings.parquet 39 | ./contrastive_vector.parquet 40 | ./prepare_data_v1.py 41 | ``` 42 | 43 | 3. Convert the data to csv format 44 | 45 | ```bash 46 | cd ~/RecSys2024_CTR_Challenge/data/Ebnerd/ 47 | python prepare_data_v1.py 48 | ``` 49 | 50 | ### Environment 51 | 52 | Please set up the environment as follows. We run the experiments on a P100 GPU server with 16G GPU memory and 750G RAM. 53 | 54 | + torch==1.10.2+cu113 55 | + fuxictr==2.2.3 56 | 57 | ``` 58 | conda create -n fuxictr python==3.9 59 | pip install -r requirements.txt 60 | source activate fuxictr 61 | ``` 62 | 63 | ### Version 1 64 | 65 | 1. Train the model on train and validation sets: 66 | 67 | ``` 68 | python run_param_tuner.py --config config/DIN_ebnerd_large_x1_tuner_config_01.yaml --gpu 0 69 | ``` 70 | 71 | We get validation avgAUC: 0.7113. Note that in FuxiCTR, AUC is the global AUC, while avgAUC is averaged over impression ID groups. 72 | 73 | 2. Make predictions on the test set: 74 | 75 | Get the experiment_id from running logs or the result csv file, and then you can run prediction on the test. 76 | 77 | ``` 78 | python submit.py --config config/DIN_ebnerd_large_x1_tuner_config_01 --expid DIN_ebnerd_large_x1_001_1860e41e --gpu 1 79 | ``` 80 | 81 | 3. Make a submission. We get test AUC: 0.7154. 82 | 83 |
84 | 85 |
86 | 87 | ### Potential Improvements 88 | 89 | + To build the baseline, we simply reuse the DIN model, which is popular for sequential user interest modeling. We encourage to explore some other alternatives for user behavior sequence modeling. 90 | + We currently only consider the click behaviors, but leave out other important singnals of reading times and percentiles. It is desired to consider them with multi-objective modeling. 91 | + We use contrast vectors and image embeddings in a straightforward way. It is interesting to explore other embedding features. 92 | + How to bridge the user sequence modeling with large pretrained models (e.g., Bert, LLMs) is a promising direction to explore. 93 | 94 | ### Discussion 95 | We also welcome contributors to help improve the space and time efficiency of FuxiCTR for handling large-scale sequence datasets. If you have any question, please feel free to open an issue. 96 | -------------------------------------------------------------------------------- /src/DIN.py: -------------------------------------------------------------------------------- 1 | # ========================================================================= 2 | # Copyright (C) 2024. FuxiCTR Authors. All rights reserved. 3 | # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # ========================================================================= 17 | 18 | import torch 19 | from torch import nn 20 | import numpy as np 21 | from pandas.core.common import flatten 22 | from fuxictr.pytorch.models import BaseModel 23 | from fuxictr.pytorch.layers import FeatureEmbeddingDict, MLP_Block, DIN_Attention, Dice 24 | 25 | 26 | class DIN(BaseModel): 27 | def __init__(self, 28 | feature_map, 29 | model_id="DIN", 30 | gpu=-1, 31 | dnn_hidden_units=[512, 128, 64], 32 | dnn_activations="ReLU", 33 | attention_hidden_units=[64], 34 | attention_hidden_activations="Dice", 35 | attention_output_activation=None, 36 | attention_dropout=0, 37 | learning_rate=1e-3, 38 | embedding_dim=10, 39 | net_dropout=0, 40 | batch_norm=False, 41 | din_target_field=[("item_id", "cate_id")], 42 | din_sequence_field=[("click_history", "cate_history")], 43 | din_use_softmax=False, 44 | embedding_regularizer=None, 45 | net_regularizer=None, 46 | **kwargs): 47 | super(DIN, self).__init__(feature_map, 48 | model_id=model_id, 49 | gpu=gpu, 50 | embedding_regularizer=embedding_regularizer, 51 | net_regularizer=net_regularizer, 52 | **kwargs) 53 | if not isinstance(din_target_field, list): 54 | din_target_field = [din_target_field] 55 | self.din_target_field = din_target_field 56 | if not isinstance(din_sequence_field, list): 57 | din_sequence_field = [din_sequence_field] 58 | self.din_sequence_field = din_sequence_field 59 | assert len(self.din_target_field) == len(self.din_sequence_field), \ 60 | "len(din_target_field) != len(din_sequence_field)" 61 | if isinstance(dnn_activations, str) and dnn_activations.lower() == "dice": 62 | dnn_activations = [Dice(units) for units in dnn_hidden_units] 63 | self.feature_map = feature_map 64 | self.embedding_dim = embedding_dim 65 | self.embedding_layer = FeatureEmbeddingDict(feature_map, embedding_dim) 66 | self.attention_layers = nn.ModuleList( 67 | [DIN_Attention(embedding_dim * len(target_field) if type(target_field) == tuple \ 68 | else embedding_dim, 69 | attention_units=attention_hidden_units, 70 | hidden_activations=attention_hidden_activations, 71 | output_activation=attention_output_activation, 72 | dropout_rate=attention_dropout, 73 | use_softmax=din_use_softmax) 74 | for target_field in self.din_target_field]) 75 | self.dnn = MLP_Block(input_dim=feature_map.sum_emb_out_dim(), 76 | output_dim=1, 77 | hidden_units=dnn_hidden_units, 78 | hidden_activations=dnn_activations, 79 | output_activation=self.output_activation, 80 | dropout_rates=net_dropout, 81 | batch_norm=batch_norm) 82 | self.compile(kwargs["optimizer"], kwargs["loss"], learning_rate) 83 | self.reset_parameters() 84 | self.model_to_device() 85 | 86 | def forward(self, inputs): 87 | X = self.get_inputs(inputs) 88 | feature_emb_dict = self.embedding_layer(X) 89 | for idx, (target_field, sequence_field) in enumerate(zip(self.din_target_field, 90 | self.din_sequence_field)): 91 | target_emb = self.get_embedding(target_field, feature_emb_dict) 92 | sequence_emb = self.get_embedding(sequence_field, feature_emb_dict) 93 | seq_field = list(flatten([sequence_field]))[0] # flatten nested list to pick the first sequence field 94 | mask = X[seq_field].long() != 0 # padding_idx = 0 required 95 | pooling_emb = self.attention_layers[idx](target_emb, sequence_emb, mask) 96 | for field, field_emb in zip(list(flatten([sequence_field])), 97 | pooling_emb.split(self.embedding_dim, dim=-1)): 98 | feature_emb_dict[field] = field_emb 99 | feature_emb = self.embedding_layer.dict2tensor(feature_emb_dict, flatten_emb=True) 100 | y_pred = self.dnn(feature_emb) 101 | return_dict = {"y_pred": y_pred} 102 | return return_dict 103 | 104 | def get_embedding(self, field, feature_emb_dict): 105 | if type(field) == tuple: 106 | emb_list = [feature_emb_dict[f] for f in field] 107 | return torch.cat(emb_list, dim=-1) 108 | else: 109 | return feature_emb_dict[field] 110 | 111 | -------------------------------------------------------------------------------- /config/DIN_ebnerd_large_x1_tuner_config_01.yaml: -------------------------------------------------------------------------------- 1 | base_config: ./config/base_config/ 2 | base_expid: DIN_default 3 | dataset_id: ebnerd_large_x1 4 | 5 | dataset_config: 6 | ebnerd_large_x1: 7 | data_root: ./data/ 8 | data_format: csv 9 | train_data: ./data/Ebnerd_large_x1/train.csv 10 | valid_data: ./data/Ebnerd_large_x1/valid.csv 11 | test_data: ./data//Ebnerd_large_x1/test.csv 12 | min_categr_count: 10 13 | data_block_size: 100000 14 | streaming: True 15 | feature_cols: 16 | - {name: impression_id, active: True, dtype: int, type: meta, remap: False} 17 | - {name: user_id, active: True, dtype: str, type: categorical} 18 | - {name: article_id, active: True, dtype: str, type: categorical} 19 | - {name: trigger_id, active: True, dtype: str, type: categorical} 20 | - {name: device_type, active: True, dtype: str, type: categorical} 21 | - {name: is_sso_user, active: True, dtype: str, type: categorical} 22 | - {name: gender, active: True, dtype: str, type: categorical} 23 | - {name: postcode, active: True, dtype: str, type: categorical} 24 | - {name: age, active: True, dtype: str, type: categorical} 25 | - {name: is_subscriber, active: True, dtype: str, type: categorical} 26 | - {name: premium, active: True, dtype: str, type: categorical} 27 | - {name: article_type, active: True, dtype: str, type: categorical} 28 | - {name: ner_clusters, active: True, dtype: str, type: sequence, splitter: ^, max_len: 5, padding: pre} 29 | - {name: topics, active: True, dtype: str, type: sequence, splitter: ^, max_len: 5, padding: pre} 30 | - {name: category, active: True, dtype: str, type: categorical} 31 | - {name: subcategory, active: True, dtype: str, type: sequence, splitter: ^, max_len: 5, padding: pre} 32 | - {name: total_inviews, active: False, dtype: float, type: numeric, fill_na: 0} 33 | - {name: total_pageviews, active: False, dtype: float, type: numeric, fill_na: 0} 34 | - {name: total_read_time, active: False, dtype: float, type: numeric, fill_na: 0} 35 | - {name: sentiment_score, active: False, dtype: float, type: numeric, fill_na: 0} 36 | - {name: sentiment_label, active: True, dtype: str, type: categorical} 37 | - {name: subcat1, active: True, dtype: str, type: categorical} 38 | - {name: hist_id, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, share_embedding: article_id} 39 | - {name: hist_cat, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, share_embedding: category} 40 | - {name: hist_subcat1, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, share_embedding: subcat1} 41 | - {name: hist_sentiment, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, share_embedding: sentiment_label} 42 | - {name: hist_type, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, share_embedding: article_type} 43 | - {name: publish_days, active: True, dtype: str, type: categorical} 44 | - {name: publish_hours, active: True, dtype: str, type: categorical} 45 | - {name: impression_hour, active: True, dtype: str, type: categorical} 46 | - {name: impression_weekday, active: True, dtype: str, type: categorical} 47 | - {name: pulish_3day, active: True, dtype: str, type: categorical} 48 | - {name: pulish_7day, active: True, dtype: str, type: categorical} 49 | - {name: article_id_img, active: True, dtype: str, type: categorical, freeze_emb: True, 50 | preprocess: "copy_from(article_id)", pretrain_dim: 64, pretrained_emb: "./data/Ebnerd_large_x1/image_emb_dim64.npz", 51 | pretrain_usage: "init", min_categr_count: 1} 52 | - {name: article_id_text, active: True, dtype: str, type: categorical, freeze_emb: True, 53 | preprocess: "copy_from(article_id)", pretrain_dim: 64, pretrained_emb: "./data/Ebnerd_large_x1/contrast_emb_dim64.npz", 54 | pretrain_usage: "init", min_categr_count: 1} 55 | - {name: hist_id_img, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, freeze_emb: True, 56 | preprocess: "copy_from(hist_id)", pretrain_dim: 64, pretrained_emb: "./data/Ebnerd_large_x1/image_emb_dim64.npz", 57 | pretrain_usage: "init", min_categr_count: 1, share_embedding: article_id_img} 58 | - {name: hist_id_text, active: True, dtype: str, type: sequence, splitter: ^, max_len: 50, padding: pre, freeze_emb: True, 59 | preprocess: "copy_from(hist_id)", pretrain_dim: 64, pretrained_emb: "./data/Ebnerd_large_x1/contrast_emb_dim64.npz", 60 | pretrain_usage: "init", min_categr_count: 1, share_embedding: article_id_text} 61 | label_col: {name: click, dtype: float} 62 | 63 | 64 | tuner_space: 65 | model_root: './checkpoints/' 66 | feature_specs: [[ 67 | {name: hist_id, feature_encoder: null}, 68 | {name: hist_cat, feature_encoder: null}, 69 | {name: hist_subcat1, feature_encoder: null}, 70 | {name: hist_sentiment, feature_encoder: null}, 71 | {name: hist_type, feature_encoder: null}, 72 | {name: hist_id_img, feature_encoder: "nn.Linear(64, 64, bias=False)"}, 73 | {name: hist_id_text, feature_encoder: ["nn.Linear(64, 64, bias=False)"]}, 74 | {name: article_id_img, feature_encoder: ["nn.Linear(64, 64, bias=False)"]}, 75 | {name: article_id_text, feature_encoder: ["nn.Linear(64, 64, bias=False)"]} 76 | ]] 77 | embedding_dim: 64 78 | dnn_hidden_units: [[1024, 512, 256]] 79 | attention_hidden_units: [[512, 256]] 80 | attention_hidden_activations: ReLU 81 | dnn_activations: ReLU 82 | attention_output_activation: null 83 | din_sequence_field: [[!!python/tuple [hist_id, hist_cat, hist_subcat1, hist_sentiment, hist_type], !!python/tuple [hist_id_img, hist_id_text]]] 84 | din_target_field: [[!!python/tuple [article_id, category, subcat1, sentiment_label, article_type], !!python/tuple [article_id_img, article_id_text]]] 85 | din_use_softmax: False 86 | embedding_regularizer: 1.e-4 87 | attention_dropout: 0.2 88 | net_dropout: 0.1 89 | batch_norm: False 90 | learning_rate: 1.e-3 91 | batch_size: 8192 92 | seed: 20242025 93 | group_id: impression_id 94 | metrics: [[avgAUC, MRR, NDCG(k=5)]] 95 | monitor: avgAUC -------------------------------------------------------------------------------- /data/prepare_data_v1.py: -------------------------------------------------------------------------------- 1 | # ========================================================================= 2 | # Copyright (C) 2024. FuxiCTR Authors. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ========================================================================= 16 | 17 | import polars as pl 18 | import numpy as np 19 | import os 20 | from pandas.core.common import flatten 21 | from datetime import datetime 22 | from sklearn.decomposition import PCA 23 | import gc 24 | 25 | 26 | # Download the datasets and put them to the following folders 27 | train_path = "./train/" 28 | dev_path = "./validation/" 29 | test_path = "./test/" 30 | dataset_version = "Ebnerd_large_x1" 31 | image_emb_path = "image_embeddings.parquet" 32 | contrast_emb_path = "contrastive_vector.parquet" 33 | MAX_SEQ_LEN = 50 34 | 35 | print("Preprocess news info...") 36 | train_news_file = os.path.join(train_path, "articles.parquet") 37 | train_news = pl.scan_parquet(train_news_file) 38 | test_news_file = os.path.join(test_path, "articles.parquet") 39 | test_news = pl.scan_parquet(test_news_file) 40 | news = pl.concat([train_news, test_news]) 41 | news = news.unique(subset=['article_id']) 42 | news = news.fill_null("") 43 | 44 | def map_feat_id_func(df, column, seq_feat=False): 45 | feat_set = set(flatten(df[column].to_list())) 46 | map_dict = dict(zip(list(feat_set), range(1, 1 + len(feat_set)))) 47 | if seq_feat: 48 | df = df.with_columns(pl.col(column).apply(lambda x: [map_dict.get(i, 0) for i in x])) 49 | else: 50 | df = df.with_columns(pl.col(column).apply(lambda x: map_dict.get(x, 0)).cast(str)) 51 | return df 52 | 53 | def tokenize_seq(df, column, map_feat_id=True, max_seq_length=5, sep="^"): 54 | df = df.with_columns(pl.col(column).apply(lambda x: x[-max_seq_length:])) 55 | if map_feat_id: 56 | df = map_feat_id_func(df, column, seq_feat=True) 57 | df = df.with_columns(pl.col(column).apply(lambda x: f"{sep}".join(str(i) for i in x))) 58 | return df 59 | 60 | news = news.select(['article_id', 'published_time', 'last_modified_time', 'premium', 61 | 'article_type', 'ner_clusters', 'topics', 'category', 'subcategory', 62 | 'total_inviews', 'total_pageviews', 'total_read_time', 63 | 'sentiment_score', 'sentiment_label']) 64 | news = ( 65 | news.with_columns(subcat1=pl.col('subcategory').apply(lambda x: str(x[0]) if len(x) > 0 else "")) 66 | .collect() 67 | ) 68 | news2cat = dict(zip(news["article_id"].cast(str), news["category"].cast(str))) 69 | news2subcat = dict(zip(news["article_id"].cast(str), news["subcat1"].cast(str))) 70 | news = tokenize_seq(news, 'ner_clusters', map_feat_id=True) 71 | news = tokenize_seq(news, 'topics', map_feat_id=True) 72 | news = tokenize_seq(news, 'subcategory', map_feat_id=False) 73 | news = map_feat_id_func(news, "sentiment_label") 74 | news = map_feat_id_func(news, "article_type") 75 | news2sentiment = dict(zip(news["article_id"].cast(str), news["sentiment_label"])) 76 | news2type = dict(zip(news["article_id"].cast(str), news["article_type"])) 77 | print(news.head()) 78 | print("Save news info...") 79 | os.makedirs(dataset_version, exist_ok=True) 80 | with open(f"./{dataset_version}/news_info.jsonl", "w") as f: 81 | f.write(news.write_json(row_oriented=True, pretty=True)) 82 | 83 | print("Preprocess behavior data...") 84 | 85 | def join_data(data_path): 86 | history_file = os.path.join(data_path, "history.parquet") 87 | history_df = pl.scan_parquet(history_file) 88 | history_df = history_df.rename({"article_id_fixed": "hist_id", 89 | "read_time_fixed": "hist_read_time", 90 | "impression_time_fixed": "hist_time", 91 | "scroll_percentage_fixed": "hist_scroll_percent"}) 92 | history_df = tokenize_seq(history_df, 'hist_id', map_feat_id=False, max_seq_length=MAX_SEQ_LEN) 93 | # history_df["hist_time"] = history_df["hist_time"].map( 94 | # lambda x: [datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%f") for v in x[-MAX_SEQ_LEN:]]) 95 | history_df = history_df.select(["user_id", "hist_id"]) 96 | history_df = history_df.with_columns( 97 | pl.col("hist_id").apply(lambda x: "^".join([news2cat.get(i, "") for i in x.split("^")])).alias("hist_cat"), 98 | pl.col("hist_id").apply(lambda x: "^".join([news2subcat.get(i, "") for i in x.split("^")])).alias("hist_subcat1"), 99 | pl.col("hist_id").apply(lambda x: "^".join([news2sentiment.get(i, "") for i in x.split("^")])).alias("hist_sentiment"), 100 | pl.col("hist_id").apply(lambda x: "^".join([news2type.get(i, "") for i in x.split("^")])).alias("hist_type") 101 | ) 102 | history_df = history_df.collect() 103 | behavior_file = os.path.join(data_path, "behaviors.parquet") 104 | sample_df = pl.scan_parquet(behavior_file) 105 | if "test/" in data_path: 106 | sample_df = ( 107 | sample_df.rename({"article_ids_inview": "article_id"}) 108 | .explode('article_id') 109 | ) 110 | sample_df = sample_df.with_columns( 111 | pl.lit(None).alias("trigger_id"), 112 | pl.lit(0).alias("click") 113 | ) 114 | else: 115 | sample_df = ( 116 | sample_df.rename({"article_id": "trigger_id"}) 117 | .rename({"article_ids_inview": "article_id"}) 118 | .explode('article_id') 119 | .with_columns(click=pl.col("article_id").is_in(pl.col("article_ids_clicked")).cast(pl.Int8)) 120 | .drop(["article_ids_clicked"]) 121 | ) 122 | sample_df = ( 123 | sample_df.collect() 124 | .join(news, on='article_id', how="left") 125 | .join(history_df, on='user_id', how="left") 126 | .with_columns( 127 | publish_days=(pl.col('impression_time') - pl.col('published_time')).dt.days().cast(pl.Int32), 128 | publish_hours=(pl.col('impression_time') - pl.col('published_time')).dt.hours().cast(pl.Int32), 129 | impression_hour=pl.col('impression_time').dt.hour().cast(pl.Int32), 130 | impression_weekday=pl.col('impression_time').dt.weekday().cast(pl.Int32) 131 | ) 132 | .with_columns( 133 | pl.col("publish_days").clip_max(3).alias("pulish_3day"), 134 | pl.col("publish_days").clip_max(7).alias("pulish_7day"), 135 | pl.col("publish_days").clip_max(30), 136 | pl.col("publish_hours").clip_max(24) 137 | ) 138 | .drop(["impression_time", "published_time", "last_modified_time"]) 139 | ) 140 | print(sample_df.columns) 141 | return sample_df 142 | 143 | train_df = join_data(train_path) 144 | print(train_df.head()) 145 | print("Train samples", train_df.shape) 146 | train_df.write_csv(f"./{dataset_version}/train.csv") 147 | del train_df 148 | 149 | valid_df = join_data(dev_path) 150 | print(valid_df.head()) 151 | print("Validation samples", valid_df.shape) 152 | valid_df.write_csv(f"./{dataset_version}/valid.csv") 153 | del valid_df 154 | gc.collect() 155 | 156 | test_df = join_data(test_path) 157 | print(test_df.head()) 158 | print("Test samples", test_df.shape) 159 | test_df.write_csv(f"./{dataset_version}/test.csv") 160 | del test_df 161 | gc.collect() 162 | 163 | print("Preprocess pretrained embeddings...") 164 | image_emb_df = pl.read_parquet(image_emb_path) 165 | pca = PCA(n_components=64) 166 | image_emb = pca.fit_transform(np.array(image_emb_df["image_embedding"].to_list())) 167 | print("image_embedding.shape", image_emb.shape) 168 | item_dict = { 169 | "key": image_emb_df["article_id"].cast(str), 170 | "value": image_emb 171 | } 172 | print("Save image_emb_dim64.npz...") 173 | np.savez(f"./{dataset_version}/image_emb_dim64.npz", **item_dict) 174 | 175 | contrast_emb_df = pl.read_parquet(contrast_emb_path) 176 | contrast_emb = pca.fit_transform(np.array(contrast_emb_df["contrastive_vector"].to_list())) 177 | print("contrast_emb.shape", contrast_emb.shape) 178 | item_dict = { 179 | "key": contrast_emb_df["article_id"].cast(str), 180 | "value": contrast_emb 181 | } 182 | print("Save contrast_emb_dim64.npz...") 183 | np.savez(f"./{dataset_version}/contrast_emb_dim64.npz", **item_dict) 184 | 185 | print("All done.") 186 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2024] FuxiCTR Team 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------