text
stringlengths
81
112k
雪球登陆, 需要设置 cookies :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/2016/08/02/cookie/ :return: def login(self, user=None, password=None, **kwargs): """ 雪球登陆, 需要设置 cookies :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/2016/08/02/cookie/ :return: """ cookies = kwargs.get('cookies') if cookies is None: raise TypeError('雪球登陆需要设置 cookies, 具体见' 'https://smalltool.github.io/2016/08/02/cookie/') headers = self._generate_headers() self.s.headers.update(headers) self.s.get(self.LOGIN_PAGE) cookie_dict = helpers.parse_cookies_str(cookies) self.s.cookies.update(cookie_dict) log.info('登录成功')
跟踪 joinquant 对应的模拟交易,支持多用户多策略 :param users: 支持 easytrader 的用户对象,支持使用 [] 指定多个用户 :param strategies: 雪球组合名, 类似 ZH123450 :param total_assets: 雪球组合对应的总资产, 格式 [组合1对应资金, 组合2对应资金] 若 strategies=['ZH000001', 'ZH000002'], 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元 假设组合 ZH000001 加仓 价格为 p 股票 A 10%, 则对应的交易指令为 买入 股票 A 价格 P 股数 1w * 10% / p 并按 100 取整 :param adjust_sell: 是否根据用户的实际持仓数调整卖出股票数量, 当卖出股票数大于实际持仓数时,调整为实际持仓数。目前仅在银河客户端测试通过。 当 users 为多个时,根据第一个 user 的持仓数决定 :type adjust_sell: bool :param initial_assets: 雪球组合对应的初始资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 总资产由 初始资产 × 组合净值 算得, total_assets 会覆盖此参数 :param track_interval: 轮训模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒 :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令 :param slippage: 滑点,0.0 表示无滑点, 0.05 表示滑点为 5% def follow( # type: ignore self, users, strategies, total_assets=10000, initial_assets=None, adjust_sell=False, track_interval=10, trade_cmd_expire_seconds=120, cmd_cache=True, slippage: float = 0.0): """跟踪 joinquant 对应的模拟交易,支持多用户多策略 :param users: 支持 easytrader 的用户对象,支持使用 [] 指定多个用户 :param strategies: 雪球组合名, 类似 ZH123450 :param total_assets: 雪球组合对应的总资产, 格式 [组合1对应资金, 组合2对应资金] 若 strategies=['ZH000001', 'ZH000002'], 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元 假设组合 ZH000001 加仓 价格为 p 股票 A 10%, 则对应的交易指令为 买入 股票 A 价格 P 股数 1w * 10% / p 并按 100 取整 :param adjust_sell: 是否根据用户的实际持仓数调整卖出股票数量, 当卖出股票数大于实际持仓数时,调整为实际持仓数。目前仅在银河客户端测试通过。 当 users 为多个时,根据第一个 user 的持仓数决定 :type adjust_sell: bool :param initial_assets: 雪球组合对应的初始资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 总资产由 初始资产 × 组合净值 算得, total_assets 会覆盖此参数 :param track_interval: 轮训模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒 :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令 :param slippage: 滑点,0.0 表示无滑点, 0.05 表示滑点为 5% """ super().follow(users=users, strategies=strategies, track_interval=track_interval, trade_cmd_expire_seconds=trade_cmd_expire_seconds, cmd_cache=cmd_cache, slippage=slippage) self._adjust_sell = adjust_sell self._users = self.warp_list(users) strategies = self.warp_list(strategies) total_assets = self.warp_list(total_assets) initial_assets = self.warp_list(initial_assets) if cmd_cache: self.load_expired_cmd_cache() self.start_trader_thread(self._users, trade_cmd_expire_seconds) for strategy_url, strategy_total_assets, strategy_initial_assets in zip( strategies, total_assets, initial_assets): assets = self.calculate_assets(strategy_url, strategy_total_assets, strategy_initial_assets) try: strategy_id = self.extract_strategy_id(strategy_url) strategy_name = self.extract_strategy_name(strategy_url) except: log.error('抽取交易id和策略名失败, 无效模拟交易url: %s', strategy_url) raise strategy_worker = Thread( target=self.track_strategy_worker, args=[strategy_id, strategy_name], kwargs={ 'interval': track_interval, 'assets': assets }) strategy_worker.start() log.info('开始跟踪策略: %s', strategy_name)
根据实际持仓值计算雪球卖出股数 因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。 导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。 而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量, 导致卖出失败 :param stock_code: 证券代码 :type stock_code: str :param amount: 卖出股份数 :type amount: int :return: 考虑实际持仓之后的卖出股份数 :rtype: int def _adjust_sell_amount(self, stock_code, amount): """ 根据实际持仓值计算雪球卖出股数 因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。 导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。 而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量, 导致卖出失败 :param stock_code: 证券代码 :type stock_code: str :param amount: 卖出股份数 :type amount: int :return: 考虑实际持仓之后的卖出股份数 :rtype: int """ stock_code = stock_code[-6:] user = self._users[0] position = user.position try: stock = next(s for s in position if s['证券代码'] == stock_code) except StopIteration: log.info('根据持仓调整 %s 卖出额,发现未持有股票 %s, 不做任何调整', stock_code, stock_code) return amount available_amount = stock['可用余额'] if available_amount >= amount: return amount adjust_amount = available_amount // 100 * 100 log.info('股票 %s 实际可用余额 %s, 指令卖出股数为 %s, 调整为 %s', stock_code, available_amount, amount, adjust_amount) return adjust_amount
获取组合信息 def _get_portfolio_info(self, portfolio_code): """ 获取组合信息 """ url = self.PORTFOLIO_URL + portfolio_code portfolio_page = self.s.get(url) match_info = re.search(r'(?<=SNB.cubeInfo = ).*(?=;\n)', portfolio_page.text) if match_info is None: raise Exception( 'cant get portfolio info, portfolio url : {}'.format(url)) try: portfolio_info = json.loads(match_info.group()) except Exception as e: raise Exception('get portfolio info error: {}'.format(e)) return portfolio_info
parse cookies str to dict :param cookies: cookies str :type cookies: str :return: cookie dict :rtype: dict def parse_cookies_str(cookies): """ parse cookies str to dict :param cookies: cookies str :type cookies: str :return: cookie dict :rtype: dict """ cookie_dict = {} for record in cookies.split(";"): key, value = record.strip().split("=", 1) cookie_dict[key] = value return cookie_dict
判断股票ID对应的证券市场 匹配规则 ['50', '51', '60', '90', '110'] 为 sh ['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz ['5', '6', '9'] 开头的为 sh, 其余为 sz :param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断 :return 'sh' or 'sz def get_stock_type(stock_code): """判断股票ID对应的证券市场 匹配规则 ['50', '51', '60', '90', '110'] 为 sh ['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz ['5', '6', '9'] 开头的为 sh, 其余为 sz :param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断 :return 'sh' or 'sz'""" stock_code = str(stock_code) if stock_code.startswith(("sh", "sz")): return stock_code[:2] if stock_code.startswith( ("50", "51", "60", "73", "90", "110", "113", "132", "204", "78") ): return "sh" if stock_code.startswith( ("00", "13", "18", "15", "16", "18", "20", "30", "39", "115", "1318") ): return "sz" if stock_code.startswith(("5", "6", "9")): return "sh" return "sz"
识别验证码,返回识别后的字符串,使用 tesseract 实现 :param image_path: 图片路径 :param broker: 券商 ['ht', 'yjb', 'gf', 'yh'] :return recognized: verify code string def recognize_verify_code(image_path, broker="ht"): """识别验证码,返回识别后的字符串,使用 tesseract 实现 :param image_path: 图片路径 :param broker: 券商 ['ht', 'yjb', 'gf', 'yh'] :return recognized: verify code string""" if broker == "gf": return detect_gf_result(image_path) if broker in ["yh_client", "gj_client"]: return detect_yh_client_result(image_path) # 调用 tesseract 识别 return default_verify_code_detect(image_path)
封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker def detect_yh_client_result(image_path): """封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker""" api = "http://yh.ez.shidenggui.com:5000/yh_client" with open(image_path, "rb") as f: rep = requests.post(api, files={"image": f}) if rep.status_code != 201: error = rep.json()["message"] raise exceptions.TradeError("request {} error: {}".format(api, error)) return rep.json()["result"]
获得用于查询的默认日期, 今天的日期, 以及30天前的日期 用于查询的日期格式通常为 20160211 :return: def get_30_date(): """ 获得用于查询的默认日期, 今天的日期, 以及30天前的日期 用于查询的日期格式通常为 20160211 :return: """ now = datetime.datetime.now() end_date = now.date() start_date = end_date - datetime.timedelta(days=30) return start_date.strftime("%Y%m%d"), end_date.strftime("%Y%m%d")
查询今天可以申购的新股信息 :return: 今日可申购新股列表 apply_code申购代码 price发行价格 def get_today_ipo_data(): """ 查询今天可以申购的新股信息 :return: 今日可申购新股列表 apply_code申购代码 price发行价格 """ agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0" send_headers = { "Host": "xueqiu.com", "User-Agent": agent, "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "deflate", "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest", "Referer": "https://xueqiu.com/hq", "Connection": "keep-alive", } timestamp = random.randint(1000000000000, 9999999999999) home_page_url = "https://xueqiu.com" ipo_data_url = ( "https://xueqiu.com/proipo/query.json?column=symbol,name,onl_subcode,onl_subbegdate,actissqty,onl" "_actissqty,onl_submaxqty,iss_price,onl_lotwiner_stpub_date,onl_lotwinrt,onl_lotwin_amount,stock_" "income&orderBy=onl_subbegdate&order=desc&stockType=&page=1&size=30&_=%s" % (str(timestamp)) ) session = requests.session() session.get(home_page_url, headers=send_headers) # 产生cookies ipo_response = session.post(ipo_data_url, headers=send_headers) json_data = json.loads(ipo_response.text) today_ipo = [] for line in json_data["data"]: if datetime.datetime.now().strftime("%a %b %d") == line[3][:10]: today_ipo.append( { "stock_code": line[0], "stock_name": line[1], "apply_code": line[2], "price": line[7], } ) return today_ipo
登陆接口 :param user: 用户名 :param password: 密码 :param kwargs: 其他参数 :return: def login(self, user=None, password=None, **kwargs): """ 登陆接口 :param user: 用户名 :param password: 密码 :param kwargs: 其他参数 :return: """ headers = self._generate_headers() self.s.headers.update(headers) # init cookie self.s.get(self.LOGIN_PAGE) # post for login params = self.create_login_params(user, password, **kwargs) rep = self.s.post(self.LOGIN_API, data=params) self.check_login_success(rep) log.info("登录成功")
跟踪平台对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: 雪球组合名, 类似 ZH123450 :param total_assets: 雪球组合对应的总资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 若 strategies=['ZH000001', 'ZH000002'] 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元, 假设组合 ZH000001 加仓 价格为 p 股票 A 10%, 则对应的交易指令为 买入 股票 A 价格 P 股数 1w * 10% / p 并按 100 取整 :param initial_assets:雪球组合对应的初始资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 总资产由 初始资产 × 组合净值 算得, total_assets 会覆盖此参数 :param track_interval: 轮询模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒 :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令 :param slippage: 滑点,0.0 表示无滑点, 0.05 表示滑点为 5% def follow( self, users, strategies, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, slippage: float = 0.0, **kwargs ): """跟踪平台对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: 雪球组合名, 类似 ZH123450 :param total_assets: 雪球组合对应的总资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 若 strategies=['ZH000001', 'ZH000002'] 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元, 假设组合 ZH000001 加仓 价格为 p 股票 A 10%, 则对应的交易指令为 买入 股票 A 价格 P 股数 1w * 10% / p 并按 100 取整 :param initial_assets:雪球组合对应的初始资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 总资产由 初始资产 × 组合净值 算得, total_assets 会覆盖此参数 :param track_interval: 轮询模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒 :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令 :param slippage: 滑点,0.0 表示无滑点, 0.05 表示滑点为 5% """ self.slippage = slippage
计算考虑滑点之后的价格 :param action: 交易动作, 支持 ['buy', 'sell'] :param price: 原始交易价格 :return: 考虑滑点后的交易价格 def _calculate_price_by_slippage(self, action: str, price: float) -> float: """ 计算考虑滑点之后的价格 :param action: 交易动作, 支持 ['buy', 'sell'] :param price: 原始交易价格 :return: 考虑滑点后的交易价格 """ if action == "buy": return price * (1 + self.slippage) if action == "sell": return price * (1 - self.slippage) return price
跟踪下单worker :param strategy: 策略id :param name: 策略名字 :param interval: 轮询策略的时间间隔,单位为秒 def track_strategy_worker(self, strategy, name, interval=10, **kwargs): """跟踪下单worker :param strategy: 策略id :param name: 策略名字 :param interval: 轮询策略的时间间隔,单位为秒""" while True: try: transactions = self.query_strategy_transaction( strategy, **kwargs ) # pylint: disable=broad-except except Exception as e: log.exception("无法获取策略 %s 调仓信息, 错误: %s, 跳过此次调仓查询", name, e) time.sleep(3) continue for transaction in transactions: trade_cmd = { "strategy": strategy, "strategy_name": name, "action": transaction["action"], "stock_code": transaction["stock_code"], "amount": transaction["amount"], "price": transaction["price"], "datetime": transaction["datetime"], } if self.is_cmd_expired(trade_cmd): continue log.info( "策略 [%s] 发送指令到交易队列, 股票: %s 动作: %s 数量: %s 价格: %s 信号产生时间: %s", name, trade_cmd["stock_code"], trade_cmd["action"], trade_cmd["amount"], trade_cmd["price"], trade_cmd["datetime"], ) self.trade_queue.put(trade_cmd) self.add_cmd_to_expired_cmds(trade_cmd) try: for _ in range(interval): time.sleep(1) except KeyboardInterrupt: log.info("程序退出") break
分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return: def _execute_trade_cmd( self, trade_cmd, users, expire_seconds, entrust_prop, send_interval ): """分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return: """ for user in users: # check expire now = datetime.datetime.now() expire = (now - trade_cmd["datetime"]).total_seconds() if expire > expire_seconds: log.warning( "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格: %s)超时,指令产生时间: %s 当前时间: %s, 超过设置的最大过期时间 %s 秒, 被丢弃", trade_cmd["strategy_name"], trade_cmd["stock_code"], trade_cmd["action"], trade_cmd["amount"], trade_cmd["price"], trade_cmd["datetime"], now, expire_seconds, ) break # check price price = trade_cmd["price"] if not self._is_number(price) or price <= 0: log.warning( "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格: %s)超时,指令产生时间: %s 当前时间: %s, 价格无效 , 被丢弃", trade_cmd["strategy_name"], trade_cmd["stock_code"], trade_cmd["action"], trade_cmd["amount"], trade_cmd["price"], trade_cmd["datetime"], now, ) break # check amount if trade_cmd["amount"] <= 0: log.warning( "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格: %s)超时,指令产生时间: %s 当前时间: %s, 买入股数无效 , 被丢弃", trade_cmd["strategy_name"], trade_cmd["stock_code"], trade_cmd["action"], trade_cmd["amount"], trade_cmd["price"], trade_cmd["datetime"], now, ) break actual_price = self._calculate_price_by_slippage( trade_cmd["action"], trade_cmd["price"] ) args = { "security": trade_cmd["stock_code"], "price": actual_price, "amount": trade_cmd["amount"], "entrust_prop": entrust_prop, } try: response = getattr(user, trade_cmd["action"])(**args) except exceptions.TradeError as e: trader_name = type(user).__name__ err_msg = "{}: {}".format(type(e).__name__, e.args) log.error( "%s 执行 策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格(考虑滑点): %s 指令产生时间: %s) 失败, 错误信息: %s", trader_name, trade_cmd["strategy_name"], trade_cmd["stock_code"], trade_cmd["action"], trade_cmd["amount"], actual_price, trade_cmd["datetime"], err_msg, ) else: log.info( "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格(考虑滑点): %s 指令产生时间: %s) 执行成功, 返回: %s", trade_cmd["strategy_name"], trade_cmd["stock_code"], trade_cmd["action"], trade_cmd["amount"], actual_price, trade_cmd["datetime"], response, )
:param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足 def trade_worker( self, users, expire_seconds=120, entrust_prop="limit", send_interval=0 ): """ :param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足 """ while True: trade_cmd = self.trade_queue.get() self._execute_trade_cmd( trade_cmd, users, expire_seconds, entrust_prop, send_interval ) time.sleep(send_interval)
设置雪球 cookies,代码来自于 https://github.com/shidenggui/easytrader/issues/269 :param cookies: 雪球 cookies :type cookies: str def _set_cookies(self, cookies): """设置雪球 cookies,代码来自于 https://github.com/shidenggui/easytrader/issues/269 :param cookies: 雪球 cookies :type cookies: str """ cookie_dict = helpers.parse_cookies_str(cookies) self.s.cookies.update(cookie_dict)
转换参数到登录所需的字典格式 :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/2016/08/02/cookie/ :param portfolio_code: 组合代码 :param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn' :return: def _prepare_account(self, user="", password="", **kwargs): """ 转换参数到登录所需的字典格式 :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/2016/08/02/cookie/ :param portfolio_code: 组合代码 :param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn' :return: """ if "portfolio_code" not in kwargs: raise TypeError("雪球登录需要设置 portfolio_code(组合代码) 参数") if "portfolio_market" not in kwargs: kwargs["portfolio_market"] = "cn" if "cookies" not in kwargs: raise TypeError( "雪球登陆需要设置 cookies, 具体见" "https://smalltool.github.io/2016/08/02/cookie/" ) self.account_config = { "cookies": kwargs["cookies"], "portfolio_code": kwargs["portfolio_code"], "portfolio_market": kwargs["portfolio_market"], }
通过雪球的接口获取股票详细信息 :param code: 股票代码 000001 :return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325', u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09, u'ind_id': 100014, u'percent': -9.31, u'current': 10.62, u'hasexist': None, u'flag': 1, u'ind_name': u'房地产', u'type': None, u'enName': None} ** flag : 未上市(0)、正常(1)、停牌(2)、涨跌停(3)、退市(4) def _search_stock_info(self, code): """ 通过雪球的接口获取股票详细信息 :param code: 股票代码 000001 :return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325', u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09, u'ind_id': 100014, u'percent': -9.31, u'current': 10.62, u'hasexist': None, u'flag': 1, u'ind_name': u'房地产', u'type': None, u'enName': None} ** flag : 未上市(0)、正常(1)、停牌(2)、涨跌停(3)、退市(4) """ data = { "code": str(code), "size": "300", "key": "47bce5c74f", "market": self.account_config["portfolio_market"], } r = self.s.get(self.config["search_stock_url"], params=data) stocks = json.loads(r.text) stocks = stocks["stocks"] stock = None if len(stocks) > 0: stock = stocks[0] return stock
获取组合信息 :return: 字典 def _get_portfolio_info(self, portfolio_code): """ 获取组合信息 :return: 字典 """ url = self.config["portfolio_url"] + portfolio_code html = self._get_html(url) match_info = re.search(r"(?<=SNB.cubeInfo = ).*(?=;\n)", html) if match_info is None: raise Exception( "cant get portfolio info, portfolio html : {}".format(html) ) try: portfolio_info = json.loads(match_info.group()) except Exception as e: raise Exception("get portfolio info error: {}".format(e)) return portfolio_info
获取账户资金状况 :return: def get_balance(self): """ 获取账户资金状况 :return: """ portfolio_code = self.account_config.get("portfolio_code", "ch") portfolio_info = self._get_portfolio_info(portfolio_code) asset_balance = self._virtual_to_balance( float(portfolio_info["net_value"]) ) # 总资产 position = portfolio_info["view_rebalancing"] # 仓位结构 cash = asset_balance * float(position["cash"]) / 100 market = asset_balance - cash return [ { "asset_balance": asset_balance, "current_balance": cash, "enable_balance": cash, "market_value": market, "money_type": u"人民币", "pre_interest": 0.25, } ]
获取雪球持仓 :return: def _get_position(self): """ 获取雪球持仓 :return: """ portfolio_code = self.account_config["portfolio_code"] portfolio_info = self._get_portfolio_info(portfolio_code) position = portfolio_info["view_rebalancing"] # 仓位结构 stocks = position["holdings"] # 持仓股票 return stocks
获取持仓 :return: def get_position(self): """ 获取持仓 :return: """ xq_positions = self._get_position() balance = self.get_balance()[0] position_list = [] for pos in xq_positions: volume = pos["weight"] * balance["asset_balance"] / 100 position_list.append( { "cost_price": volume / 100, "current_amount": 100, "enable_amount": 100, "income_balance": 0, "keep_cost_price": volume / 100, "last_price": volume / 100, "market_value": volume, "position_str": "random", "stock_code": pos["stock_symbol"], "stock_name": pos["stock_name"], } ) return position_list
获取雪球调仓历史 :param instance: :param owner: :return: def _get_xq_history(self): """ 获取雪球调仓历史 :param instance: :param owner: :return: """ data = { "cube_symbol": str(self.account_config["portfolio_code"]), "count": 20, "page": 1, } resp = self.s.get(self.config["history_url"], params=data) res = json.loads(resp.text) return res["list"]
获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return: def get_entrust(self): """ 获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return: """ xq_entrust_list = self._get_xq_history() entrust_list = [] replace_none = lambda s: s or 0 for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调仓状态 if status == "pending": status = "已报" elif status in ["canceled", "failed"]: status = "废单" else: status = "已成" for entrust in xq_entrusts["rebalancing_histories"]: price = entrust["price"] entrust_list.append( { "entrust_no": entrust["id"], "entrust_bs": u"买入" if entrust["target_weight"] > replace_none(entrust["prev_weight"]) else u"卖出", "report_time": self._time_strftime( entrust["updated_at"] ), "entrust_status": status, "stock_code": entrust["stock_symbol"], "stock_name": entrust["stock_name"], "business_amount": 100, "business_price": price, "entrust_amount": 100, "entrust_price": price, } ) return entrust_list
对未成交的调仓进行伪撤单 :param entrust_no: :return: def cancel_entrust(self, entrust_no): """ 对未成交的调仓进行伪撤单 :param entrust_no: :return: """ xq_entrust_list = self._get_xq_history() is_have = False for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调仓状态 for entrust in xq_entrusts["rebalancing_histories"]: if entrust["id"] == entrust_no and status == "pending": is_have = True buy_or_sell = ( "buy" if entrust["target_weight"] < entrust["weight"] else "sell" ) if ( entrust["target_weight"] == 0 and entrust["weight"] == 0 ): raise exceptions.TradeError(u"移除的股票操作无法撤销,建议重新买入") balance = self.get_balance()[0] volume = ( abs(entrust["target_weight"] - entrust["weight"]) * balance["asset_balance"] / 100 ) r = self._trade( security=entrust["stock_symbol"], volume=volume, entrust_bs=buy_or_sell, ) if len(r) > 0 and "error_info" in r[0]: raise exceptions.TradeError( u"撤销失败!%s" % ("error_info" in r[0]) ) if not is_have: raise exceptions.TradeError(u"撤销对象已失效") return True
雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 def adjust_weight(self, stock_code, weight): """ 雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 """ stock = self._search_stock_info(stock_code) if stock is None: raise exceptions.TradeError(u"没有查询要操作的股票信息") if stock["flag"] != 1: raise exceptions.TradeError(u"未上市、停牌、涨跌停、退市的股票无法操作。") # 仓位比例向下取两位数 weight = round(weight, 2) # 获取原有仓位信息 position_list = self._get_position() # 调整后的持仓 for position in position_list: if position["stock_id"] == stock["stock_id"]: position["proactive"] = True position["weight"] = weight if weight != 0 and stock["stock_id"] not in [ k["stock_id"] for k in position_list ]: position_list.append( { "code": stock["code"], "name": stock["name"], "enName": stock["enName"], "hasexist": stock["hasexist"], "flag": stock["flag"], "type": stock["type"], "current": stock["current"], "chg": stock["chg"], "percent": str(stock["percent"]), "stock_id": stock["stock_id"], "ind_id": stock["ind_id"], "ind_name": stock["ind_name"], "ind_color": stock["ind_color"], "textname": stock["name"], "segment_name": stock["ind_name"], "weight": weight, "url": "/S/" + stock["code"], "proactive": True, "price": str(stock["current"]), } ) remain_weight = 100 - sum(i.get("weight") for i in position_list) cash = round(remain_weight, 2) log.debug("调仓比例:%f, 剩余持仓 :%f", weight, remain_weight) data = { "cash": cash, "holdings": str(json.dumps(position_list)), "cube_symbol": str(self.account_config["portfolio_code"]), "segment": "true", "comment": "", } try: resp = self.s.post(self.config["rebalance_url"], data=data) # pylint: disable=broad-except except Exception as e: log.warning("调仓失败: %s ", e) return None log.debug("调仓 %s: 持仓比例%d", stock["name"], weight) resp_json = json.loads(resp.text) if "error_description" in resp_json and resp.status_code != 200: log.error("调仓错误: %s", resp_json["error_description"]) return [ { "error_no": resp_json["error_code"], "error_info": resp_json["error_description"], } ] log.debug("调仓成功 %s: 持仓比例%d", stock["name"], weight) return None
调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): """ 调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: """ stock = self._search_stock_info(security) balance = self.get_balance()[0] if stock is None: raise exceptions.TradeError(u"没有查询要操作的股票信息") if not volume: volume = int(float(price) * amount) # 可能要取整数 if balance["current_balance"] < volume and entrust_bs == "buy": raise exceptions.TradeError(u"没有足够的现金进行操作") if stock["flag"] != 1: raise exceptions.TradeError(u"未上市、停牌、涨跌停、退市的股票无法操作。") if volume == 0: raise exceptions.TradeError(u"操作金额不能为零") # 计算调仓调仓份额 weight = volume / balance["asset_balance"] * 100 weight = round(weight, 2) # 获取原有仓位信息 position_list = self._get_position() # 调整后的持仓 is_have = False for position in position_list: if position["stock_id"] == stock["stock_id"]: is_have = True position["proactive"] = True old_weight = position["weight"] if entrust_bs == "buy": position["weight"] = weight + old_weight else: if weight > old_weight: raise exceptions.TradeError(u"操作数量大于实际可卖出数量") else: position["weight"] = old_weight - weight position["weight"] = round(position["weight"], 2) if not is_have: if entrust_bs == "buy": position_list.append( { "code": stock["code"], "name": stock["name"], "enName": stock["enName"], "hasexist": stock["hasexist"], "flag": stock["flag"], "type": stock["type"], "current": stock["current"], "chg": stock["chg"], "percent": str(stock["percent"]), "stock_id": stock["stock_id"], "ind_id": stock["ind_id"], "ind_name": stock["ind_name"], "ind_color": stock["ind_color"], "textname": stock["name"], "segment_name": stock["ind_name"], "weight": round(weight, 2), "url": "/S/" + stock["code"], "proactive": True, "price": str(stock["current"]), } ) else: raise exceptions.TradeError(u"没有持有要卖出的股票") if entrust_bs == "buy": cash = ( (balance["current_balance"] - volume) / balance["asset_balance"] * 100 ) else: cash = ( (balance["current_balance"] + volume) / balance["asset_balance"] * 100 ) cash = round(cash, 2) log.debug("weight:%f, cash:%f", weight, cash) data = { "cash": cash, "holdings": str(json.dumps(position_list)), "cube_symbol": str(self.account_config["portfolio_code"]), "segment": 1, "comment": "", } try: resp = self.s.post(self.config["rebalance_url"], data=data) # pylint: disable=broad-except except Exception as e: log.warning("调仓失败: %s ", e) return None else: log.debug( "调仓 %s%s: %d", entrust_bs, stock["name"], resp.status_code ) resp_json = json.loads(resp.text) if "error_description" in resp_json and resp.status_code != 200: log.error("调仓错误: %s", resp_json["error_description"]) return [ { "error_no": resp_json["error_code"], "error_info": resp_json["error_description"], } ] return [ { "entrust_no": resp_json["id"], "init_date": self._time_strftime(resp_json["created_at"]), "batch_no": "委托批号", "report_no": "申报号", "seat_no": "席位编号", "entrust_time": self._time_strftime( resp_json["updated_at"] ), "entrust_price": price, "entrust_amount": amount, "stock_code": security, "entrust_bs": "买入", "entrust_type": "雪球虚拟委托", "entrust_status": "-", } ]
买入卖出股票 :param security: 股票代码 :param price: 买入价格 :param amount: 买入股数 :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: def buy(self, security, price=0, amount=0, volume=0, entrust_prop=0): """买入卖出股票 :param security: 股票代码 :param price: 买入价格 :param amount: 买入股数 :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: """ return self._trade(security, price, amount, volume, "buy")
卖出股票 :param security: 股票代码 :param price: 卖出价格 :param amount: 卖出股数 :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: def sell(self, security, price=0, amount=0, volume=0, entrust_prop=0): """卖出股票 :param security: 股票代码 :param price: 卖出价格 :param amount: 卖出股数 :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: """ return self._trade(security, price, amount, volume, "sell")
跟踪joinquant对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: joinquant 的模拟交易地址,支持使用 [] 指定多个模拟交易, 地址类似 https://www.joinquant.com/algorithm/live/index?backtestId=xxx :param track_interval: 轮训模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒 :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令 :param entrust_prop: 委托方式, 'limit' 为限价,'market' 为市价, 仅在银河实现 :param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时卖出单没有及时成交导致的买入金额不足 def follow( self, users, strategies, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, entrust_prop="limit", send_interval=0, ): """跟踪joinquant对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: joinquant 的模拟交易地址,支持使用 [] 指定多个模拟交易, 地址类似 https://www.joinquant.com/algorithm/live/index?backtestId=xxx :param track_interval: 轮训模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒 :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令 :param entrust_prop: 委托方式, 'limit' 为限价,'market' 为市价, 仅在银河实现 :param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时卖出单没有及时成交导致的买入金额不足 """ users = self.warp_list(users) strategies = self.warp_list(strategies) if cmd_cache: self.load_expired_cmd_cache() self.start_trader_thread( users, trade_cmd_expire_seconds, entrust_prop, send_interval ) workers = [] for strategy_url in strategies: try: strategy_id = self.extract_strategy_id(strategy_url) strategy_name = self.extract_strategy_name(strategy_url) except: log.error("抽取交易id和策略名失败, 无效的模拟交易url: %s", strategy_url) raise strategy_worker = Thread( target=self.track_strategy_worker, args=[strategy_id, strategy_name], kwargs={"interval": track_interval}, ) strategy_worker.start() workers.append(strategy_worker) log.info("开始跟踪策略: %s", strategy_name) for worker in workers: worker.join()
直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return: def connect(self, exe_path=None, **kwargs): """ 直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return: """ connect_path = exe_path or self._config.DEFAULT_EXE_PATH if connect_path is None: raise ValueError( "参数 exe_path 未设置,请设置客户端对应的 exe 地址,类似 C:\\客户端安装目录\\xiadan.exe" ) self._app = pywinauto.Application().connect( path=connect_path, timeout=10 ) self._close_prompt_windows() self._main = self._app.top_window()
市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} def market_buy(self, security, amount, ttype=None, **kwargs): """ 市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} """ self._switch_left_menus(["市价委托", "买入"]) return self.market_trade(security, amount, ttype)
市价卖出 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} def market_sell(self, security, amount, ttype=None, **kwargs): """ 市价卖出 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} """ self._switch_left_menus(["市价委托", "卖出"]) return self.market_trade(security, amount, ttype)
市价交易 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} def market_trade(self, security, amount, ttype=None, **kwargs): """ 市价交易 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} """ self._set_market_trade_params(security, amount) if ttype is not None: self._set_market_trade_type(ttype) self._submit_trade() return self._handle_pop_dialogs( handler_class=pop_dialog_handler.TradePopDialogHandler )
根据选择的市价交易类型选择对应的下拉选项 def _set_market_trade_type(self, ttype): """根据选择的市价交易类型选择对应的下拉选项""" selects = self._main.child_window( control_id=self._config.TRADE_MARKET_TYPE_CONTROL_ID, class_name="ComboBox", ) for i, text in selects.texts(): # skip 0 index, because 0 index is current select index if i == 0: continue if ttype in text: selects.select(i - 1) break else: raise TypeError("不支持对应的市价类型: {}".format(ttype))
登陆客户端 :param config_path: 登陆配置文件,跟参数登陆方式二选一 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :param comm_password: 通讯密码 :return: def prepare( self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, **kwargs ): """ 登陆客户端 :param config_path: 登陆配置文件,跟参数登陆方式二选一 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :param comm_password: 通讯密码 :return: """ if config_path is not None: account = helpers.file2dict(config_path) user = account["user"] password = account["password"] comm_password = account.get("comm_password") exe_path = account.get("exe_path") self.login( user, password, exe_path or self._config.DEFAULT_EXE_PATH, comm_password, **kwargs )
登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 :return: def login(self, user, password, exe_path, comm_password=None, **kwargs): """ 登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 :return: """ try: self._app = pywinauto.Application().connect( path=self._run_exe_path(exe_path), timeout=1 ) # pylint: disable=broad-except except Exception: self._app = pywinauto.Application().start(exe_path) is_xiadan = True if "xiadan.exe" in exe_path else False # wait login window ready while True: try: self._app.top_window().Edit1.wait("ready") break except RuntimeError: pass self._app.top_window().Edit1.type_keys(user) self._app.top_window().Edit2.type_keys(password) while True: self._app.top_window().Edit3.type_keys( self._handle_verify_code(is_xiadan) ) self._app.top_window()["确定" if is_xiadan else "登录"].click() # detect login is success or not try: self._app.top_window().wait_not("exists visible", 10) break # pylint: disable=broad-except except Exception: if is_xiadan: self._app.top_window()["确定"].click() self._app = pywinauto.Application().connect( path=self._run_exe_path(exe_path), timeout=10 ) self._close_prompt_windows() self._main = self._app.window(title="网上股票交易系统5.0") try: self._main.child_window( control_id=129, class_name="SysTreeView32" ).wait("ready", 2) # pylint: disable=broad-except except Exception: self.wait(2) self._switch_window_to_normal_mode()
用于生成特定的券商对象 :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端'] :param debug: 控制 debug 日志的显示, 默认为 True :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万 :return the class of trader Usage:: >>> import easytrader >>> user = easytrader.use('xq') >>> user.prepare('xq.json') def use(broker, debug=True, **kwargs): """用于生成特定的券商对象 :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端'] :param debug: 控制 debug 日志的显示, 默认为 True :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万 :return the class of trader Usage:: >>> import easytrader >>> user = easytrader.use('xq') >>> user.prepare('xq.json') """ if not debug: log.setLevel(logging.INFO) if broker.lower() in ["xq", "雪球"]: return XueQiuTrader(**kwargs) if broker.lower() in ["yh_client", "银河客户端"]: from .yh_clienttrader import YHClientTrader return YHClientTrader() if broker.lower() in ["ht_client", "华泰客户端"]: from .ht_clienttrader import HTClientTrader return HTClientTrader() if broker.lower() in ["gj_client", "国金客户端"]: from .gj_clienttrader import GJClientTrader return GJClientTrader() if broker.lower() in ["ths", "同花顺客户端"]: from .clienttrader import ClientTrader return ClientTrader() raise NotImplementedError
用于生成特定的券商对象 :param platform:平台支持 ['jq', 'joinquant', '聚宽’] :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万, 总资金由 initial_assets * 组合当前净值 得出 :param total_assets: [雪球参数] 控制雪球总资金,无默认值, 若设置则覆盖 initial_assets :return the class of follower Usage:: >>> import easytrader >>> user = easytrader.use('xq') >>> user.prepare('xq.json') >>> jq = easytrader.follower('jq') >>> jq.login(user='username', password='password') >>> jq.follow(users=user, strategies=['strategies_link']) def follower(platform, **kwargs): """用于生成特定的券商对象 :param platform:平台支持 ['jq', 'joinquant', '聚宽’] :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万, 总资金由 initial_assets * 组合当前净值 得出 :param total_assets: [雪球参数] 控制雪球总资金,无默认值, 若设置则覆盖 initial_assets :return the class of follower Usage:: >>> import easytrader >>> user = easytrader.use('xq') >>> user.prepare('xq.json') >>> jq = easytrader.follower('jq') >>> jq.login(user='username', password='password') >>> jq.follow(users=user, strategies=['strategies_link']) """ if platform.lower() in ["rq", "ricequant", "米筐"]: return RiceQuantFollower() if platform.lower() in ["jq", "joinquant", "聚宽"]: return JoinQuantFollower() if platform.lower() in ["xq", "xueqiu", "雪球"]: return XueQiuFollower(**kwargs) raise NotImplementedError
Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf. Produces datapoints of the format: [HWC image, label]. Note that Caffe LMDB format is not efficient: it stores serialized raw arrays rather than JPEG images. Args: lmdb_path, shuffle, keys: same as :class:`LMDBData`. Returns: a :class:`LMDBDataDecoder` instance. Example: .. code-block:: python ds = CaffeLMDB("/tmp/validation", keys='{:0>8d}') def CaffeLMDB(lmdb_path, shuffle=True, keys=None): """ Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf. Produces datapoints of the format: [HWC image, label]. Note that Caffe LMDB format is not efficient: it stores serialized raw arrays rather than JPEG images. Args: lmdb_path, shuffle, keys: same as :class:`LMDBData`. Returns: a :class:`LMDBDataDecoder` instance. Example: .. code-block:: python ds = CaffeLMDB("/tmp/validation", keys='{:0>8d}') """ cpb = get_caffe_pb() lmdb_data = LMDBData(lmdb_path, shuffle, keys) def decoder(k, v): try: datum = cpb.Datum() datum.ParseFromString(v) img = np.fromstring(datum.data, dtype=np.uint8) img = img.reshape(datum.channels, datum.height, datum.width) except Exception: log_once("Cannot read key {}".format(k), 'warn') return None return [img.transpose(1, 2, 0), datum.label] logger.warn("Caffe LMDB format doesn't store jpeg-compressed images, \ it's not recommended due to its inferior performance.") return LMDBDataDecoder(lmdb_data, decoder)
Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes def memory(self): """Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes """ class GpuMemoryInfo(Structure): _fields_ = [ ('total', c_ulonglong), ('free', c_ulonglong), ('used', c_ulonglong), ] c_memory = GpuMemoryInfo() _check_return(_NVML.get_function( "nvmlDeviceGetMemoryInfo")(self.hnd, byref(c_memory))) return {'total': c_memory.total, 'free': c_memory.free, 'used': c_memory.used}
Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written Example: >>> print(ctx.device(0).utilization()) {'gpu': 4L, 'memory': 6L} def utilization(self): """Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written Example: >>> print(ctx.device(0).utilization()) {'gpu': 4L, 'memory': 6L} """ class GpuUtilizationInfo(Structure): _fields_ = [ ('gpu', c_uint), ('memory', c_uint), ] c_util = GpuUtilizationInfo() _check_return(_NVML.get_function( "nvmlDeviceGetUtilizationRates")(self.hnd, byref(c_util))) return {'gpu': c_util.gpu, 'memory': c_util.memory}
Get number of devices def num_devices(self): """Get number of devices """ c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) device = c_nvmlDevice_t() _check_return(_NVML.get_function( "nvmlDeviceGetHandleByIndex_v2")(c_index, byref(device))) return NvidiaDevice(device)
Download and extract the tarball from Alex's website. Copied from tensorflow example def maybe_download_and_extract(dest_directory, cifar_classnum): """Download and extract the tarball from Alex's website. Copied from tensorflow example """ assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_foldername = 'cifar-100-python' if os.path.isdir(os.path.join(dest_directory, cifar_foldername)): logger.info("Found cifar{} data in {}.".format(cifar_classnum, dest_directory)) return else: DATA_URL = DATA_URL_CIFAR_10 if cifar_classnum == 10 else DATA_URL_CIFAR_100 filename = DATA_URL[0].split('/')[-1] filepath = os.path.join(dest_directory, filename) download(DATA_URL[0], dest_directory, expect_size=DATA_URL[1]) tarfile.open(filepath, 'r:gz').extractall(dest_directory)
Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: a mean image of all images in the given datasets, with size 32x32x3 def get_per_pixel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: a mean image of all images in the given datasets, with size 32x32x3 """ for name in names: assert name in ['train', 'test'], name train_files, test_files, _ = get_filenames(self.dir, self.cifar_classnum) all_files = [] if 'train' in names: all_files.extend(train_files) if 'test' in names: all_files.extend(test_files) all_imgs = [x[0] for x in read_cifar(all_files, self.cifar_classnum)] arr = np.array(all_imgs, dtype='float32') mean = np.mean(arr, axis=0) return mean
Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: An array of three values as mean of each channel, for all images in the given datasets. def get_per_channel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: An array of three values as mean of each channel, for all images in the given datasets. """ mean = self.get_per_pixel_mean(names) return np.mean(mean, axis=(0, 1))
Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): """ Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 """ num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1], axis=1) # #fgx2 mask_logits = tf.gather_nd(mask_logits, indices) # #fgxhxw mask_probs = tf.sigmoid(mask_logits) # add some training visualizations to tensorboard with tf.name_scope('mask_viz'): viz = tf.concat([fg_target_masks, mask_probs], axis=1) viz = tf.expand_dims(viz, 3) viz = tf.cast(viz * 255, tf.uint8, name='viz') tf.summary.image('mask_truth|pred', viz, max_outputs=10) loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=fg_target_masks, logits=mask_logits) loss = tf.reduce_mean(loss, name='maskrcnn_loss') pred_label = mask_probs > 0.5 truth_label = fg_target_masks > 0.5 accuracy = tf.reduce_mean( tf.cast(tf.equal(pred_label, truth_label), tf.float32), name='accuracy') pos_accuracy = tf.logical_and( tf.equal(pred_label, truth_label), tf.equal(truth_label, True)) pos_accuracy = tf.reduce_mean(tf.cast(pos_accuracy, tf.float32), name='pos_accuracy') fg_pixel_ratio = tf.reduce_mean(tf.cast(truth_label, tf.float32), name='fg_pixel_ratio') add_moving_summary(loss, accuracy, fg_pixel_ratio, pos_accuracy) return loss
Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask_logits (N x num_category x 2s x 2s): def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): """ Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask_logits (N x num_category x 2s x 2s): """ assert norm in [None, 'GN'], norm l = feature with argscope([Conv2D, Conv2DTranspose], data_format='channels_first', kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode='fan_out', distribution='untruncated_normal' if get_tf_version_tuple() >= (1, 12) else 'normal')): # c2's MSRAFill is fan_out for k in range(num_convs): l = Conv2D('fcn{}'.format(k), l, cfg.MRCNN.HEAD_DIM, 3, activation=tf.nn.relu) if norm is not None: l = GroupNorm('gn{}'.format(k), l) l = Conv2DTranspose('deconv', l, cfg.MRCNN.HEAD_DIM, 2, strides=2, activation=tf.nn.relu) l = Conv2D('conv', l, num_category, 1) return l
Args: names (tuple[str]): names of the dataset split Returns: a 32x32x3 image, the mean of all images in the given datasets def get_per_pixel_mean(names=('train', 'test', 'extra')): """ Args: names (tuple[str]): names of the dataset split Returns: a 32x32x3 image, the mean of all images in the given datasets """ for name in names: assert name in ['train', 'test', 'extra'], name images = [SVHNDigit(x).X for x in names] return np.concatenate(tuple(images)).mean(axis=0)
Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor: def build_or_reuse_placeholder(tensor_spec): """ Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor: """ g = tfv1.get_default_graph() name = tensor_spec.name try: tensor = g.get_tensor_by_name(name + ':0') assert "Placeholder" in tensor.op.type, "Tensor {} exists but is not a placeholder!".format(name) assert tensor_spec.is_compatible_with(tensor), \ "Tensor {} exists but is not compatible with the signature!".format(tensor) return tensor except KeyError: with tfv1.name_scope(None): # clear any name scope it might get called in ret = tfv1.placeholder( tensor_spec.dtype, shape=tensor_spec.shape, name=tensor_spec.name) return ret
Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this model. The result is cached for each instance of :class:`ModelDescBase`. def get_input_signature(self): """ Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this model. The result is cached for each instance of :class:`ModelDescBase`. """ with tf.Graph().as_default() as G: # create these placeholder in a temporary graph inputs = self.inputs() if isinstance(inputs[0], tf.Tensor): for p in inputs: assert "Placeholder" in p.op.type, \ "inputs() have to return TensorSpec or placeholders! Found {} instead.".format(p) assert p.graph == G, "Placeholders returned by inputs() should be created inside inputs()!" return [TensorSpec(shape=p.shape, dtype=p.dtype, name=get_op_tensor_name(p.name)[0]) for p in inputs]
Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find dependencies of. op (tf.Operation or tf.Tensor): Returns: bool: True if any one of `targets` depend on `op`. def dependency_of_targets(targets, op): """ Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find dependencies of. op (tf.Operation or tf.Tensor): Returns: bool: True if any one of `targets` depend on `op`. """ # TODO tensorarray? sparsetensor? if isinstance(op, tf.Tensor): op = op.op assert isinstance(op, tf.Operation), op from tensorflow.contrib.graph_editor import get_backward_walk_ops # alternative implementation can use graph_util.extract_sub_graph dependent_ops = get_backward_walk_ops(targets, control_inputs=True) return op in dependent_ops
Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns: bool: True if any of `fetches` depend on `op`. def dependency_of_fetches(fetches, op): """ Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns: bool: True if any of `fetches` depend on `op`. """ try: from tensorflow.python.client.session import _FetchHandler as FetchHandler # use the graph of the op, so that this function can be called without being under a default graph handler = FetchHandler(op.graph, fetches, {}) targets = tuple(handler.fetches() + handler.targets()) except ImportError: if isinstance(fetches, list): targets = tuple(fetches) elif isinstance(fetches, dict): raise ValueError("Don't know how to parse dictionary to fetch list! " "This is a bug of tensorpack.") else: targets = (fetches, ) return dependency_of_targets(targets, op)
Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. def create_scalar_summary(name, v): """ Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. """ assert isinstance(name, six.string_types), type(name) v = float(v) s = tf.Summary() s.value.add(tag=name, simple_value=v) return s
Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary: def create_image_summary(name, val): """ Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary: """ assert isinstance(name, six.string_types), type(name) n, h, w, c = val.shape val = val.astype('uint8') s = tf.Summary() imparams = [cv2.IMWRITE_PNG_COMPRESSION, 9] for k in range(n): arr = val[k] # CV2 will only write correctly in BGR chanel order if c == 3: arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) elif c == 4: arr = cv2.cvtColor(arr, cv2.COLOR_RGBA2BGRA) tag = name if n == 1 else '{}/{}'.format(name, k) retval, img_str = cv2.imencode('.png', arr, imparams) if not retval: # Encoding has failed. continue img_str = img_str.tostring() img = tf.Summary.Image() img.height = h img.width = w # 1 - grayscale 3 - RGB 4 - RGBA img.colorspace = c img.encoded_image_string = img_str s.value.add(tag=tag, image=img) return s
Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str): summary name. Defaults to be the op name. collections (list[str]): collections of the summary ops. main_tower_only (bool): Only run under main training tower. If set to True, calling this function under other TowerContext has no effect. Example: .. code-block:: python with tf.name_scope('mysummaries'): # to not mess up tensorboard add_tensor_summary( tensor, ['histogram', 'rms', 'sparsity'], name='mytensor') def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): """ Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str): summary name. Defaults to be the op name. collections (list[str]): collections of the summary ops. main_tower_only (bool): Only run under main training tower. If set to True, calling this function under other TowerContext has no effect. Example: .. code-block:: python with tf.name_scope('mysummaries'): # to not mess up tensorboard add_tensor_summary( tensor, ['histogram', 'rms', 'sparsity'], name='mytensor') """ types = set(types) if name is None: name = x.op.name ctx = get_current_tower_context() if main_tower_only and ctx is not None and not ctx.is_main_training_tower: return SUMMARY_TYPES_DIC = { 'scalar': lambda: tf.summary.scalar(name + '-summary', x, collections=collections), 'histogram': lambda: tf.summary.histogram(name + '-histogram', x, collections=collections), 'sparsity': lambda: tf.summary.scalar( name + '-sparsity', tf.nn.zero_fraction(x), collections=collections), 'mean': lambda: tf.summary.scalar( name + '-mean', tf.reduce_mean(x), collections=collections), 'rms': lambda: tf.summary.scalar( name + '-rms', rms(x), collections=collections) } for typ in types: SUMMARY_TYPES_DIC[typ]()
Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``. name (str): if is None, use x.name. collections (list[str]): collections of the summary ops. def add_activation_summary(x, types=None, name=None, collections=None): """ Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``. name (str): if is None, use x.name. collections (list[str]): collections of the summary ops. """ ndim = x.get_shape().ndims if ndim < 2: logger.warn("Cannot summarize scalar activation {}".format(x.name)) return if types is None: types = ['sparsity', 'rms', 'histogram'] with cached_name_scope('activation-summary'): add_tensor_summary(x, types, name=name, collections=collections)
Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type]). Summary type is defined in :func:`add_tensor_summary`. collections (list[str]): collections of the summary ops. Example: .. code-block:: python add_param_summary( ('.*/W', ['histogram', 'rms']), ('.*/gamma', ['scalar']), ) def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type]). Summary type is defined in :func:`add_tensor_summary`. collections (list[str]): collections of the summary ops. Example: .. code-block:: python add_param_summary( ('.*/W', ['histogram', 'rms']), ('.*/gamma', ['scalar']), ) """ collections = kwargs.pop('collections', None) assert len(kwargs) == 0, "Unknown kwargs: " + str(kwargs) ctx = get_current_tower_context() if ctx is not None and not ctx.is_main_training_tower: return params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) with cached_name_scope('param-summary'): for p in params: name = p.op.name for rgx, actions in summary_lists: if not rgx.endswith('$'): rgx = rgx + '$' if re.match(rgx, name): add_tensor_summary(p, actions, name=name, collections=collections)
Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the name of the collection to add EMA-maintaining ops. The default will work together with the default :class:`MovingAverageSummary` callback. summary_collections ([str]): the names of collections to add the summary op. Default is TF's default (`tf.GraphKeys.SUMMARIES`). Returns: [tf.Tensor]: list of tensors returned by assign_moving_average, which can be used to maintain the EMA. def add_moving_summary(*args, **kwargs): """ Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the name of the collection to add EMA-maintaining ops. The default will work together with the default :class:`MovingAverageSummary` callback. summary_collections ([str]): the names of collections to add the summary op. Default is TF's default (`tf.GraphKeys.SUMMARIES`). Returns: [tf.Tensor]: list of tensors returned by assign_moving_average, which can be used to maintain the EMA. """ decay = kwargs.pop('decay', 0.95) coll = kwargs.pop('collection', MOVING_SUMMARY_OPS_KEY) summ_coll = kwargs.pop('summary_collections', None) assert len(kwargs) == 0, "Unknown arguments: " + str(kwargs) ctx = get_current_tower_context() # allow ctx to be none if ctx is not None and not ctx.is_main_training_tower: return [] graph = tf.get_default_graph() try: control_flow_ctx = graph._get_control_flow_context() # XLA does not support summaries anyway # However, this function will generate unnecessary dependency edges, # which makes the tower function harder to compile under XLA, so we skip it if control_flow_ctx is not None and control_flow_ctx.IsXLAContext(): return except Exception: pass if tf.get_variable_scope().reuse is True: logger.warn("add_moving_summary() called under reuse=True scope, ignored.") return [] for x in args: assert isinstance(x, (tf.Tensor, tf.Variable)), x assert x.get_shape().ndims == 0, \ "add_moving_summary() only accepts scalar tensor! Got one with {}".format(x.get_shape()) ema_ops = [] for c in args: name = re.sub('tower[0-9]+/', '', c.op.name) with tf.name_scope(None): if not c.dtype.is_floating: c = tf.cast(c, tf.float32) # assign_moving_average creates variables with op names, therefore clear ns first. with _enter_vs_reuse_ns('EMA') as vs: ema_var = tf.get_variable(name, shape=c.shape, dtype=c.dtype, initializer=tf.constant_initializer(), trainable=False) ns = vs.original_name_scope with tf.name_scope(ns): # reuse VS&NS so that EMA_1 won't appear ema_op = moving_averages.assign_moving_average( ema_var, c, decay, zero_debias=True, name=name + '_EMA_apply') ema_ops.append(ema_op) with tf.name_scope(None): tf.summary.scalar( name + '-summary', ema_op, collections=summ_coll) # write the EMA value as a summary if coll is not None: for op in ema_ops: tf.add_to_collection(coll, op) return ema_ops
Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead Nx4, updated boxes def run_head(self, proposals, stage): """ Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead Nx4, updated boxes """ reg_weights = tf.constant(cfg.CASCADE.BBOX_REG_WEIGHTS[stage], dtype=tf.float32) pooled_feature = self.roi_func(proposals.boxes) # N,C,S,S pooled_feature = self.scale_gradient(pooled_feature) head_feature = self.fastrcnn_head_func('head', pooled_feature) label_logits, box_logits = fastrcnn_outputs( 'outputs', head_feature, self.num_classes, class_agnostic_regression=True) head = FastRCNNHead(proposals, box_logits, label_logits, self.gt_boxes, reg_weights) refined_boxes = head.decoded_output_boxes_class_agnostic() refined_boxes = clip_boxes(refined_boxes, self.image_shape2d) return head, tf.stop_gradient(refined_boxes, name='output_boxes')
Args: boxes: Nx4 Returns: BoxProposals def match_box_with_gt(self, boxes, iou_threshold): """ Args: boxes: Nx4 Returns: BoxProposals """ if self.is_training: with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)): iou = pairwise_iou(boxes, self.gt_boxes) # NxM max_iou_per_box = tf.reduce_max(iou, axis=1) # N best_iou_ind = tf.argmax(iou, axis=1) # N labels_per_box = tf.gather(self.gt_labels, best_iou_ind) fg_mask = max_iou_per_box >= iou_threshold fg_inds_wrt_gt = tf.boolean_mask(best_iou_ind, fg_mask) labels_per_box = tf.stop_gradient(labels_per_box * tf.cast(fg_mask, tf.int64)) return BoxProposals(boxes, labels_per_box, fg_inds_wrt_gt) else: return BoxProposals(boxes)
Returns: Nx#classx4 def decoded_output_boxes(self): """ Returns: Nx#classx4 """ ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
Returns: Nx#class def output_scores(self, name=None): """ Returns: Nx#class """ scores = [head.output_scores('cascade_scores_stage{}'.format(idx + 1)) for idx, head in enumerate(self._heads)] return tf.multiply(tf.add_n(scores), (1.0 / self.num_cascade_stages), name=name)
Visualize some intermediate results (proposals, raw predictions) inside the pipeline. def do_visualize(model, model_path, nr_visualize=100, output_dir='output'): """ Visualize some intermediate results (proposals, raw predictions) inside the pipeline. """ df = get_train_dataflow() # we don't visualize mask stuff df.reset_state() pred = OfflinePredictor(PredictConfig( model=model, session_init=get_model_loader(model_path), input_names=['image', 'gt_boxes', 'gt_labels'], output_names=[ 'generate_{}_proposals/boxes'.format('fpn' if cfg.MODE_FPN else 'rpn'), 'generate_{}_proposals/scores'.format('fpn' if cfg.MODE_FPN else 'rpn'), 'fastrcnn_all_scores', 'output/boxes', 'output/scores', 'output/labels', ])) if os.path.isdir(output_dir): shutil.rmtree(output_dir) utils.fs.mkdir_p(output_dir) with tqdm.tqdm(total=nr_visualize) as pbar: for idx, dp in itertools.islice(enumerate(df), nr_visualize): img, gt_boxes, gt_labels = dp['image'], dp['gt_boxes'], dp['gt_labels'] rpn_boxes, rpn_scores, all_scores, \ final_boxes, final_scores, final_labels = pred(img, gt_boxes, gt_labels) # draw groundtruth boxes gt_viz = draw_annotation(img, gt_boxes, gt_labels) # draw best proposals for each groundtruth, to show recall proposal_viz, good_proposals_ind = draw_proposal_recall(img, rpn_boxes, rpn_scores, gt_boxes) # draw the scores for the above proposals score_viz = draw_predictions(img, rpn_boxes[good_proposals_ind], all_scores[good_proposals_ind]) results = [DetectionResult(*args) for args in zip(final_boxes, final_scores, final_labels, [None] * len(final_labels))] final_viz = draw_final_outputs(img, results) viz = tpviz.stack_patches([ gt_viz, proposal_viz, score_viz, final_viz], 2, 2) if os.environ.get('DISPLAY', None): tpviz.interactive_imshow(viz) cv2.imwrite("{}/{:03d}.png".format(output_dir, idx), viz) pbar.update()
Args: name (str): the name of the layer, e.g. 'Conv2D' Returns: the wrapped layer function, or None if not registered. def get_registered_layer(name): """ Args: name (str): the name of the layer, e.g. 'Conv2D' Returns: the wrapped layer function, or None if not registered. """ ret = _LAYER_REGISTRY.get(name, None) if ret == _NameConflict: raise KeyError("Layer named '{}' is registered with `@layer_register` more than once!".format(name)) return ret
Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called either with or without the scope name argument, depend on whether the first argument is string or not. Returns: A decorator used to register a layer. Example: .. code-block:: python @layer_register(use_scope=True) def add10(x): return x + tf.get_variable('W', shape=[10]) # use it: output = add10('layer_name', input) # the function will be called under variable scope "layer_name". def layer_register( log_shape=False, use_scope=True): """ Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called either with or without the scope name argument, depend on whether the first argument is string or not. Returns: A decorator used to register a layer. Example: .. code-block:: python @layer_register(use_scope=True) def add10(x): return x + tf.get_variable('W', shape=[10]) # use it: output = add10('layer_name', input) # the function will be called under variable scope "layer_name". """ def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): assert args[0] is not None, args if use_scope: name, inputs = args[0], args[1] args = args[1:] # actual positional args used to call func assert isinstance(name, six.string_types), "First argument for \"{}\" should be a string. ".format( func.__name__) + "Did you forget to specify the name of the layer?" else: assert not log_shape if isinstance(args[0], six.string_types): if use_scope is False: logger.warn( "Please call layer {} without the first scope name argument, " "or register the layer with use_scope=None to allow " "two calling methods.".format(func.__name__)) name, inputs = args[0], args[1] args = args[1:] # actual positional args used to call func else: inputs = args[0] name = None if not (isinstance(inputs, (tf.Tensor, tf.Variable)) or (isinstance(inputs, (list, tuple)) and isinstance(inputs[0], (tf.Tensor, tf.Variable)))): raise ValueError("Invalid inputs to layer: " + str(inputs)) # use kwargs from current argument scope actual_args = copy.copy(get_arg_scope()[func.__name__]) # explicit kwargs overwrite argscope actual_args.update(kwargs) # if six.PY3: # # explicit positional args also override argscope. only work in PY3 # posargmap = inspect.signature(func).bind_partial(*args).arguments # for k in six.iterkeys(posargmap): # if k in actual_args: # del actual_args[k] if name is not None: # use scope with tfv1.variable_scope(name) as scope: # this name is only used to surpress logging, doesn't hurt to do some heuristics scope_name = re.sub('tower[0-9]+/', '', scope.name) do_log_shape = log_shape and scope_name not in _LAYER_LOGGED if do_log_shape: logger.info("{} input: {}".format(scope.name, get_shape_str(inputs))) # run the actual function outputs = func(*args, **actual_args) if do_log_shape: # log shape info and add activation logger.info("{} output: {}".format( scope.name, get_shape_str(outputs))) _LAYER_LOGGED.add(scope_name) else: # run the actual function outputs = func(*args, **actual_args) return outputs wrapped_func.symbolic_function = func # attribute to access the underlying function object wrapped_func.use_scope = use_scope _register(func.__name__, wrapped_func) return wrapped_func return wrapper
This method will build the trainer's tower function under ``TowerContext(is_training=False)``, and returns a callable predictor with input placeholders & output tensors in this tower. This method handles the common case of inference with the same tower function. If you want to do inference with a different tower function, you can always build the tower by yourself, under a "reuse" variable scope and a `TowerContext(is_training=False)`. Args: input_names (list): list of input names, matching the inputs declared for the trainer. output_names(list): list of tensor names without the tower prefix. device (int): build the predictor on device '/gpu:{device}' or use -1 for '/cpu:0'. Returns: an :class:`OnlinePredictor`. Example: .. code-block:: none # in the graph: interesting_tensor = tf.identity(x, name='fun') # in _setup_graph callback method: self._predictor = self.trainer.get_predictor(['input1', 'input2'], ['fun']) # After session is initialized (see Tutorials - Write a Callback), can use it by: outputs = self._predictor(input1, input2) The CycleGAN example and DQN example have more concrete use of this method. def get_predictor(self, input_names, output_names, device=0): """ This method will build the trainer's tower function under ``TowerContext(is_training=False)``, and returns a callable predictor with input placeholders & output tensors in this tower. This method handles the common case of inference with the same tower function. If you want to do inference with a different tower function, you can always build the tower by yourself, under a "reuse" variable scope and a `TowerContext(is_training=False)`. Args: input_names (list): list of input names, matching the inputs declared for the trainer. output_names(list): list of tensor names without the tower prefix. device (int): build the predictor on device '/gpu:{device}' or use -1 for '/cpu:0'. Returns: an :class:`OnlinePredictor`. Example: .. code-block:: none # in the graph: interesting_tensor = tf.identity(x, name='fun') # in _setup_graph callback method: self._predictor = self.trainer.get_predictor(['input1', 'input2'], ['fun']) # After session is initialized (see Tutorials - Write a Callback), can use it by: outputs = self._predictor(input1, input2) The CycleGAN example and DQN example have more concrete use of this method. """ assert self.tower_func is not None, "Must set tower_func on the trainer to use get_predictor()!" tower_name = 'tower-pred-{}'.format(device) if device >= 0 else 'tower-pred-cpu' device_id = device device = '/gpu:{}'.format(device_id) if device_id >= 0 else '/cpu:0' try: tower = self.tower_func.towers[tower_name] assert tower is not None, "This is a bug!" except KeyError: tower = None if tower is None: input = PlaceholderInput() input.setup(self.input_signature) vs_name = self._vs_name_for_predictor(device_id) with tfv1.variable_scope(tfv1.get_variable_scope(), reuse=True), \ tf.device(device), PredictTowerContext( tower_name, vs_name=vs_name): logger.info("Building graph for predict tower '{}' on device {} {}...".format( tower_name, device, "with variable scope '{}'".format(vs_name) if vs_name else '')) self.tower_func(*input.get_input_tensors()) tower = self.tower_func.towers[tower_name] input_tensors = tower.get_tensors(input_names) output_tensors = tower.get_tensors(output_names) predictor = OnlinePredictor(input_tensors, output_tensors) self._predictors.append(predictor) return predictor
Export trained model to use it in TensorFlow Serving or cloudML. def export_serving(model_path): """Export trained model to use it in TensorFlow Serving or cloudML. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ModelExporter(pred_config).export_serving('/tmp/exported')
Export trained model to use it as a frozen and pruned inference graph in mobile applications. def export_compact(model_path): """Export trained model to use it as a frozen and pruned inference graph in mobile applications. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) ModelExporter(pred_config).export_compact('/tmp/compact_graph.pb')
Run inference from a training model checkpoint. def apply(model_path): """Run inference from a training model checkpoint. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2.imread('lena.png') prediction = pred([img])[0] cv2.imwrite('applied_default.jpg', prediction[0])
Run inference from a different graph, which receives encoded images buffers. def apply_inference_graph(model_path): """Run inference from a different graph, which receives encoded images buffers. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) pred = OfflinePredictor(pred_config) buf = open('lena.png', 'rb').read() prediction = pred([buf])[0] with open('applied_inference_graph.png', 'wb') as f: f.write(prediction[0])
Run the pruned and frozen inference graph. def apply_compact(graph_path): """Run the pruned and frozen inference graph. """ with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def) input_img = sess.graph.get_tensor_by_name('import/input_img:0') prediction_img = sess.graph.get_tensor_by_name('import/prediction_img:0') prediction = sess.run(prediction_img, {input_img: cv2.imread('lena.png')[None, ...]}) cv2.imwrite('applied_compact.png', prediction[0])
Mostly equivalent to `tf.layers.batch_normalization`, but difference in the following: 1. Accepts `data_format` rather than `axis`. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from `TowerContext`. 4. Support the `internal_update` option. Args: internal_update (bool): if False, add EMA update ops to `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer by control dependencies. Variable Names: * ``beta``: the bias term. Will be zero-inited by default. * ``gamma``: the scale term. Will be one-inited by default. Input will be transformed by ``x * gamma + beta``. * ``mean/EMA``: the moving average of mean. * ``variance/EMA``: the moving average of variance. Note: 1. About multi-GPU training: moving averages across GPUs are not aggregated. Batch statistics are computed independently. This is consistent with most frameworks. 2. Combinations of ``training`` and ``ctx.is_training``: * ``training == ctx.is_training``: standard BN, EMA are maintained during training and used during inference. This is the default. * ``training and not ctx.is_training``: still use batch statistics in inference. * ``not training and ctx.is_training``: use EMA to normalize in training. This is useful when you load a pre-trained BN and don't want to fine tune the EMA. EMA will not be updated in this case. def BatchNorm(inputs, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=tf.ones_initializer(), data_format='channels_last', internal_update=False): """ Mostly equivalent to `tf.layers.batch_normalization`, but difference in the following: 1. Accepts `data_format` rather than `axis`. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from `TowerContext`. 4. Support the `internal_update` option. Args: internal_update (bool): if False, add EMA update ops to `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer by control dependencies. Variable Names: * ``beta``: the bias term. Will be zero-inited by default. * ``gamma``: the scale term. Will be one-inited by default. Input will be transformed by ``x * gamma + beta``. * ``mean/EMA``: the moving average of mean. * ``variance/EMA``: the moving average of variance. Note: 1. About multi-GPU training: moving averages across GPUs are not aggregated. Batch statistics are computed independently. This is consistent with most frameworks. 2. Combinations of ``training`` and ``ctx.is_training``: * ``training == ctx.is_training``: standard BN, EMA are maintained during training and used during inference. This is the default. * ``training and not ctx.is_training``: still use batch statistics in inference. * ``not training and ctx.is_training``: use EMA to normalize in training. This is useful when you load a pre-trained BN and don't want to fine tune the EMA. EMA will not be updated in this case. """ data_format = get_data_format(data_format, keras_mode=False) shape = inputs.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4] if ndims == 2: data_format = 'NHWC' if data_format == 'NCHW': n_out = shape[1] else: n_out = shape[-1] # channel assert n_out is not None, "Input to BatchNorm cannot have unknown channels!" beta, gamma, moving_mean, moving_var = get_bn_variables(n_out, scale, center, gamma_initializer) ctx = get_current_tower_context() use_local_stat = training if use_local_stat is None: use_local_stat = ctx.is_training use_local_stat = bool(use_local_stat) if use_local_stat: if ndims == 2: inputs = tf.reshape(inputs, [-1, 1, 1, n_out]) # fused_bn only takes 4D input # fused_bn has error using NCHW? (see #190) xn, batch_mean, batch_var = tf.nn.fused_batch_norm( inputs, gamma, beta, epsilon=epsilon, is_training=True, data_format=data_format) if ndims == 2: xn = tf.squeeze(xn, [1, 2]) else: if ctx.is_training: assert get_tf_version_tuple() >= (1, 4), \ "Fine tuning a BatchNorm model with fixed statistics is only " \ "supported after https://github.com/tensorflow/tensorflow/pull/12580 " if ctx.is_main_training_tower: # only warn in first tower logger.warn("[BatchNorm] Using moving_mean/moving_variance in training.") # Using moving_mean/moving_variance in training, which means we # loaded a pre-trained BN and only fine-tuning the affine part. xn, _, _ = tf.nn.fused_batch_norm( inputs, gamma, beta, mean=moving_mean, variance=moving_var, epsilon=epsilon, data_format=data_format, is_training=False) else: if ndims == 4: xn, _, _ = tf.nn.fused_batch_norm( inputs, gamma, beta, mean=moving_mean, variance=moving_var, epsilon=epsilon, data_format=data_format, is_training=False) else: xn = tf.nn.batch_normalization( inputs, moving_mean, moving_var, beta, gamma, epsilon) # maintain EMA only on one GPU is OK, even in replicated mode. # because training time doesn't use EMA if ctx.is_main_training_tower: add_model_variable(moving_mean) add_model_variable(moving_var) if ctx.is_main_training_tower and use_local_stat: ret = update_bn_ema(xn, batch_mean, batch_var, moving_mean, moving_var, momentum, internal_update) else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder(mean=moving_mean, variance=moving_var) if scale: vh.gamma = gamma if center: vh.beta = beta return ret
Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c2] def SelectComponent(ds, idxs): """ Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c2] """ return MapData(ds, lambda dp: [dp[i] for i in idxs])
Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth max_depth, max_list: same as in :meth:`__init__`. Returns: string: debug message def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): """ Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth max_depth, max_list: same as in :meth:`__init__`. Returns: string: debug message """ class _elementInfo(object): def __init__(self, el, pos, depth=0, max_list=3): self.shape = "" self.type = type(el).__name__ self.dtype = "" self.range = "" self.sub_elements = [] self.ident = " " * (depth * 2) self.pos = pos numpy_scalar_types = list(itertools.chain(*np.sctypes.values())) if isinstance(el, (int, float, bool)): self.range = " with value {}".format(el) elif type(el) is np.ndarray: self.shape = " of shape {}".format(el.shape) self.dtype = ":{}".format(str(el.dtype)) self.range = " in range [{}, {}]".format(el.min(), el.max()) elif type(el) in numpy_scalar_types: self.range = " with value {}".format(el) elif isinstance(el, (list)): self.shape = " of len {}".format(len(el)) if depth < max_depth: for k, subel in enumerate(el): if k < max_list: self.sub_elements.append(_elementInfo(subel, k, depth + 1, max_list)) else: self.sub_elements.append(" " * ((depth + 1) * 2) + '...') break else: if len(el) > 0: self.sub_elements.append(" " * ((depth + 1) * 2) + ' ...') def __str__(self): strings = [] vals = (self.ident, self.pos, self.type, self.dtype, self.shape, self.range) strings.append("{}{}: {}{}{}{}".format(*vals)) for k, el in enumerate(self.sub_elements): strings.append(str(el)) return "\n".join(strings) return str(_elementInfo(entry, k, depth, max_list))
Args: cnt(int): the count of some event of interest. tot(int): the total number of events. def feed(self, count, total=1): """ Args: cnt(int): the count of some event of interest. tot(int): the total number of events. """ self._tot += total self._cnt += count
Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. def feed(self, pred, label): """ Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. """ assert pred.shape == label.shape, "{} != {}".format(pred.shape, label.shape) self.nr_pos += (label == 1).sum() self.nr_neg += (label == 0).sum() self.nr_pred_pos += (pred == 1).sum() self.nr_pred_neg += (pred == 0).sum() self.corr_pos += ((pred == 1) & (pred == label)).sum() self.corr_neg += ((pred == 0) & (pred == label)).sum()
Args: x (float or np.ndarray): must have the same shape. def feed(self, x): """ Args: x (float or np.ndarray): must have the same shape. """ self._n += 1 delta = x - self._mean self._mean += delta * (1.0 / self._n) delta2 = x - self._mean self._M2 += delta * delta2
Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables. def apply_grad_processors(opt, gradprocs): """ Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables. """ assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs[:] super(_ApplyGradientProcessor, self).__init__(opt) def apply_gradients(self, grads_and_vars, global_step=None, name=None): g = self._apply(grads_and_vars) return self._opt.apply_gradients(g, global_step, name) def _apply(self, g): for proc in self._gradprocs: g = proc.process(g) return g return _ApplyGradientProcessor(opt, gradprocs)
Args: box: 4 float mask: MxM floats shape: h,w Returns: A uint8 binary image of hxw. def _paste_mask(box, mask, shape): """ Args: box: 4 float mask: MxM floats shape: h,w Returns: A uint8 binary image of hxw. """ # int() is floor # box fpcoor=0.0 -> intcoor=0.0 x0, y0 = list(map(int, box[:2] + 0.5)) # box fpcoor=h -> intcoor=h-1, inclusive x1, y1 = list(map(int, box[2:] - 0.5)) # inclusive x1 = max(x0, x1) # require at least 1x1 y1 = max(y0, y1) w = x1 + 1 - x0 h = y1 + 1 - y0 # rounding errors could happen here, because masks were not originally computed for this shape. # but it's hard to do better, because the network does not know the "original" scale mask = (cv2.resize(mask, (w, h)) > 0.5).astype('uint8') ret = np.zeros(shape, dtype='uint8') ret[y0:y1 + 1, x0:x1 + 1] = mask return ret
Run detection on one image, using the TF callable. This function should handle the preprocessing internally. Args: img: an image model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) Returns: [DetectionResult] def predict_image(img, model_func): """ Run detection on one image, using the TF callable. This function should handle the preprocessing internally. Args: img: an image model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) Returns: [DetectionResult] """ orig_shape = img.shape[:2] resizer = CustomResize(cfg.PREPROC.TEST_SHORT_EDGE_SIZE, cfg.PREPROC.MAX_SIZE) resized_img = resizer.augment(img) scale = np.sqrt(resized_img.shape[0] * 1.0 / img.shape[0] * resized_img.shape[1] / img.shape[1]) boxes, probs, labels, *masks = model_func(resized_img) boxes = boxes / scale # boxes are already clipped inside the graph, but after the floating point scaling, this may not be true any more. boxes = clip_boxes(boxes, orig_shape) if masks: # has mask full_masks = [_paste_mask(box, mask, orig_shape) for box, mask in zip(boxes, masks[0])] masks = full_masks else: # fill with none masks = [None] * len(boxes) results = [DetectionResult(*args) for args in zip(boxes, probs, labels.tolist(), masks)] return results
Args: df: a DataFlow which produces (image, image_id) model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) tqdm_bar: a tqdm object to be shared among multiple evaluation instances. If None, will create a new one. Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` def predict_dataflow(df, model_func, tqdm_bar=None): """ Args: df: a DataFlow which produces (image, image_id) model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) tqdm_bar: a tqdm object to be shared among multiple evaluation instances. If None, will create a new one. Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` """ df.reset_state() all_results = [] with ExitStack() as stack: # tqdm is not quite thread-safe: https://github.com/tqdm/tqdm/issues/323 if tqdm_bar is None: tqdm_bar = stack.enter_context(get_tqdm(total=df.size())) for img, img_id in df: results = predict_image(img, model_func) for r in results: # int()/float() to make it json-serializable res = { 'image_id': img_id, 'category_id': int(r.class_id), 'bbox': [round(float(x), 4) for x in r.box], 'score': round(float(r.score), 4), } # also append segmentation to results if r.mask is not None: rle = cocomask.encode( np.array(r.mask[:, :, None], order='F'))[0] rle['counts'] = rle['counts'].decode('ascii') res['segmentation'] = rle all_results.append(res) tqdm_bar.update(1) return all_results
Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` def multithread_predict_dataflow(dataflows, model_funcs): """ Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` """ num_worker = len(model_funcs) assert len(dataflows) == num_worker if num_worker == 1: return predict_dataflow(dataflows[0], model_funcs[0]) kwargs = {'thread_name_prefix': 'EvalWorker'} if sys.version_info.minor >= 6 else {} with ThreadPoolExecutor(max_workers=num_worker, **kwargs) as executor, \ tqdm.tqdm(total=sum([df.size() for df in dataflows])) as pbar: futures = [] for dataflow, pred in zip(dataflows, model_funcs): futures.append(executor.submit(predict_dataflow, dataflow, pred, pbar)) all_results = list(itertools.chain(*[fut.result() for fut in futures])) return all_results
Flatten the tensor except the first dimension. def batch_flatten(x): """ Flatten the tensor except the first dimension. """ shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
A wrapper around `tf.layers.Dense`. One difference to maintain backward-compatibility: Default weight initializer is variance_scaling_initializer(2.0). Variable Names: * ``W``: weights of shape [in_dim, out_dim] * ``b``: bias def FullyConnected( inputs, units, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): """ A wrapper around `tf.layers.Dense`. One difference to maintain backward-compatibility: Default weight initializer is variance_scaling_initializer(2.0). Variable Names: * ``W``: weights of shape [in_dim, out_dim] * ``b``: bias """ if kernel_initializer is None: if get_tf_version_tuple() <= (1, 12): kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0) else: kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal') inputs = batch_flatten(inputs) with rename_get_variable({'kernel': 'W', 'bias': 'b'}): layer = tf.layers.Dense( units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, _reuse=tf.get_variable_scope().reuse) ret = layer.apply(inputs, scope=tf.get_variable_scope()) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=layer.kernel) if use_bias: ret.variables.b = layer.bias return ret
Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs def _init_runtime(self): """ Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs """ if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = OfflinePredictor(self.config) if self.idx == 0: with self.predictor.graph.as_default(): describe_trainable_vars()
Fetch a batch of data without waiting def fetch_batch(self): """ Fetch a batch of data without waiting""" inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) while len(futures) < self.batch_size: try: inp, f = self.queue.get_nowait() for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) except queue.Empty: break # do not wait for k in range(nr_input_var): batched[k] = np.asarray(batched[k]) return batched, futures
Same as in :meth:`AsyncPredictorBase.put_task`. def put_task(self, dp, callback=None): """ Same as in :meth:`AsyncPredictorBase.put_task`. """ f = Future() if callback is not None: f.add_done_callback(callback) self.input_queue.put((dp, f)) return f
Args: buf: the output of `dumps`. def loads_msgpack(buf): """ Args: buf: the output of `dumps`. """ # Since 0.6, the default max size was set to 1MB. # We change it to approximately 1G. return msgpack.loads(buf, raw=False, max_bin_len=MAX_MSGPACK_LEN, max_array_len=MAX_MSGPACK_LEN, max_map_len=MAX_MSGPACK_LEN, max_str_len=MAX_MSGPACK_LEN)
Almost equivalent to `tf.layers.batch_normalization`, but different (and more powerful) in the following: 1. Accepts an alternative `data_format` option when `axis` is None. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from tensorpack's `TowerContext`, but can be overwritten. 4. Support the `internal_update` option, which cover more use cases than the standard collection-based update. 5. Support the `sync_statistics` option, which is very useful in small-batch models. Args: internal_update (bool): if False, add EMA update ops to `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer by control dependencies. They are very similar in speed, but `internal_update=True` is recommended and can be helpful when: 1. BatchNorm is used inside dynamic control flow. The collection-based update does not support dynamic control flows. 2. BatchNorm layer is sometimes unused (e.g., when you have two networks to train alternatively). Putting all update ops into a single collection will waste a lot of compute. Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/14699 sync_statistics (str or None): one of None, "nccl", or "horovod". By default (None), it uses statistics of the input tensor to normalize during training. This is the standard way BatchNorm was implemented in most frameworks. When set to "nccl", this layer must be used under tensorpack's multi-GPU trainers. It uses the aggregated statistics of the whole batch (across all GPUs) to normalize. When set to "horovod", this layer must be used under tensorpack's :class:`HorovodTrainer`. It uses the aggregated statistics of the whole batch (across all MPI ranks) to normalize. Note that on single machine this is significantly slower than the "nccl" implementation. When enabled, per-GPU E[x] and E[x^2] among all GPUs are averaged to compute global mean & variance. Therefore each GPU needs to have the same batch size. The synchronization is based on the current variable scope + the name of the layer (`BatchNorm('name', input)`). Therefore, you need to make sure that: 1. The BatchNorm layer on different GPUs needs to have the same name, so that statistics can be synchronized. If names do not match, this layer will hang. 2. Different BatchNorm layers in one tower cannot share the same name. 3. A BatchNorm layer needs to be executed for the same number of times by all GPUs. If different GPUs execute one BatchNorm layer for different number of times (e.g., if some GPUs do not execute it), this layer may hang. This option only has effect when `training == get_current_tower_context().training == True`. This option is also known as "Cross-GPU BatchNorm" as mentioned in: `MegDet: A Large Mini-Batch Object Detector <https://arxiv.org/abs/1711.07240>`_. Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/18222. When `sync_statistics` is enabled, `internal_update` will be set to True automatically. This is to avoid running `UPDATE_OPS`, which requires synchronization. Variable Names: * ``beta``: the bias term. Will be zero-inited by default. * ``gamma``: the scale term. Will be one-inited by default. * ``mean/EMA``: the moving average of mean. * ``variance/EMA``: the moving average of variance. Note: Combinations of ``training`` and ``ctx.is_training``: * ``training == ctx.is_training``: standard BN, EMA are maintained during training and used during inference. This is the default. * ``training and not ctx.is_training``: still use batch statistics in inference. * ``not training and ctx.is_training``: use EMA to normalize in training. This is useful when you load a pre-trained BN and don't want to fine tune the EMA. EMA will not be updated in this case. def BatchNorm(inputs, axis=None, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, beta_initializer=tf.zeros_initializer(), gamma_initializer=tf.ones_initializer(), virtual_batch_size=None, data_format='channels_last', internal_update=False, sync_statistics=None): """ Almost equivalent to `tf.layers.batch_normalization`, but different (and more powerful) in the following: 1. Accepts an alternative `data_format` option when `axis` is None. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from tensorpack's `TowerContext`, but can be overwritten. 4. Support the `internal_update` option, which cover more use cases than the standard collection-based update. 5. Support the `sync_statistics` option, which is very useful in small-batch models. Args: internal_update (bool): if False, add EMA update ops to `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer by control dependencies. They are very similar in speed, but `internal_update=True` is recommended and can be helpful when: 1. BatchNorm is used inside dynamic control flow. The collection-based update does not support dynamic control flows. 2. BatchNorm layer is sometimes unused (e.g., when you have two networks to train alternatively). Putting all update ops into a single collection will waste a lot of compute. Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/14699 sync_statistics (str or None): one of None, "nccl", or "horovod". By default (None), it uses statistics of the input tensor to normalize during training. This is the standard way BatchNorm was implemented in most frameworks. When set to "nccl", this layer must be used under tensorpack's multi-GPU trainers. It uses the aggregated statistics of the whole batch (across all GPUs) to normalize. When set to "horovod", this layer must be used under tensorpack's :class:`HorovodTrainer`. It uses the aggregated statistics of the whole batch (across all MPI ranks) to normalize. Note that on single machine this is significantly slower than the "nccl" implementation. When enabled, per-GPU E[x] and E[x^2] among all GPUs are averaged to compute global mean & variance. Therefore each GPU needs to have the same batch size. The synchronization is based on the current variable scope + the name of the layer (`BatchNorm('name', input)`). Therefore, you need to make sure that: 1. The BatchNorm layer on different GPUs needs to have the same name, so that statistics can be synchronized. If names do not match, this layer will hang. 2. Different BatchNorm layers in one tower cannot share the same name. 3. A BatchNorm layer needs to be executed for the same number of times by all GPUs. If different GPUs execute one BatchNorm layer for different number of times (e.g., if some GPUs do not execute it), this layer may hang. This option only has effect when `training == get_current_tower_context().training == True`. This option is also known as "Cross-GPU BatchNorm" as mentioned in: `MegDet: A Large Mini-Batch Object Detector <https://arxiv.org/abs/1711.07240>`_. Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/18222. When `sync_statistics` is enabled, `internal_update` will be set to True automatically. This is to avoid running `UPDATE_OPS`, which requires synchronization. Variable Names: * ``beta``: the bias term. Will be zero-inited by default. * ``gamma``: the scale term. Will be one-inited by default. * ``mean/EMA``: the moving average of mean. * ``variance/EMA``: the moving average of variance. Note: Combinations of ``training`` and ``ctx.is_training``: * ``training == ctx.is_training``: standard BN, EMA are maintained during training and used during inference. This is the default. * ``training and not ctx.is_training``: still use batch statistics in inference. * ``not training and ctx.is_training``: use EMA to normalize in training. This is useful when you load a pre-trained BN and don't want to fine tune the EMA. EMA will not be updated in this case. """ # parse shapes data_format = get_data_format(data_format, keras_mode=False) shape = inputs.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4], ndims if sync_statistics is not None: sync_statistics = sync_statistics.lower() assert sync_statistics in [None, 'nccl', 'horovod'], sync_statistics if axis is None: if ndims == 2: axis = 1 else: axis = 1 if data_format == 'NCHW' else 3 assert axis in [1, 3], axis num_chan = shape[axis] # parse training/ctx ctx = get_current_tower_context() if training is None: training = ctx.is_training training = bool(training) TF_version = get_tf_version_tuple() freeze_bn_backward = not training and ctx.is_training if freeze_bn_backward: assert TF_version >= (1, 4), \ "Fine tuning a BatchNorm model with fixed statistics needs TF>=1.4!" if ctx.is_main_training_tower: # only warn in first tower logger.warn("[BatchNorm] Using moving_mean/moving_variance in training.") # Using moving_mean/moving_variance in training, which means we # loaded a pre-trained BN and only fine-tuning the affine part. if sync_statistics is None or not (training and ctx.is_training): coll_bk = backup_collection([tf.GraphKeys.UPDATE_OPS]) with rename_get_variable( {'moving_mean': 'mean/EMA', 'moving_variance': 'variance/EMA'}): tf_args = dict( axis=axis, momentum=momentum, epsilon=epsilon, center=center, scale=scale, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, # https://github.com/tensorflow/tensorflow/issues/10857#issuecomment-410185429 fused=(ndims == 4 and axis in [1, 3] and not freeze_bn_backward), _reuse=tf.get_variable_scope().reuse) if TF_version >= (1, 5): tf_args['virtual_batch_size'] = virtual_batch_size else: assert virtual_batch_size is None, "Feature not supported in this version of TF!" use_fp16 = inputs.dtype == tf.float16 if use_fp16: # non-fused does not support fp16; fused does not support all layouts. # we made our best guess here tf_args['fused'] = True layer = tf.layers.BatchNormalization(**tf_args) xn = layer.apply(inputs, training=training, scope=tf.get_variable_scope()) # maintain EMA only on one GPU is OK, even in replicated mode. # because during training, EMA isn't used if ctx.is_main_training_tower: for v in layer.non_trainable_variables: if isinstance(v, tf.Variable): tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) if not ctx.is_main_training_tower or internal_update: restore_collection(coll_bk) if training and internal_update: assert layer.updates with tf.control_dependencies(layer.updates): ret = tf.identity(xn, name='output') else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder( moving_mean=layer.moving_mean, mean=layer.moving_mean, # for backward-compatibility moving_variance=layer.moving_variance, variance=layer.moving_variance) # for backward-compatibility if scale: vh.gamma = layer.gamma if center: vh.beta = layer.beta else: red_axis = [0] if ndims == 2 else ([0, 2, 3] if axis == 1 else [0, 1, 2]) new_shape = None # don't need to reshape unless ... if ndims == 4 and axis == 1: new_shape = [1, num_chan, 1, 1] batch_mean = tf.reduce_mean(inputs, axis=red_axis) batch_mean_square = tf.reduce_mean(tf.square(inputs), axis=red_axis) if sync_statistics == 'nccl': num_dev = ctx.total if num_dev == 1: logger.warn("BatchNorm(sync_statistics='nccl') is used with only one tower!") else: assert six.PY2 or TF_version >= (1, 10), \ "Cross-GPU BatchNorm is only supported in TF>=1.10 ." \ "Upgrade TF or apply this patch manually: https://github.com/tensorflow/tensorflow/pull/20360" if TF_version <= (1, 12): try: from tensorflow.contrib.nccl.python.ops.nccl_ops import _validate_and_load_nccl_so except Exception: pass else: _validate_and_load_nccl_so() from tensorflow.contrib.nccl.ops import gen_nccl_ops else: from tensorflow.python.ops import gen_nccl_ops shared_name = re.sub('tower[0-9]+/', '', tf.get_variable_scope().name) batch_mean = gen_nccl_ops.nccl_all_reduce( input=batch_mean, reduction='sum', num_devices=num_dev, shared_name=shared_name + '_NCCL_mean') * (1.0 / num_dev) batch_mean_square = gen_nccl_ops.nccl_all_reduce( input=batch_mean_square, reduction='sum', num_devices=num_dev, shared_name=shared_name + '_NCCL_mean_square') * (1.0 / num_dev) elif sync_statistics == 'horovod': # Require https://github.com/uber/horovod/pull/331 import horovod.tensorflow as hvd if hvd.size() == 1: logger.warn("BatchNorm(sync_statistics='horovod') is used with only one process!") else: import horovod hvd_version = tuple(map(int, horovod.__version__.split('.'))) assert hvd_version >= (0, 13, 6), "sync_statistics=horovod needs horovod>=0.13.6 !" batch_mean = hvd.allreduce(batch_mean, average=True) batch_mean_square = hvd.allreduce(batch_mean_square, average=True) batch_var = batch_mean_square - tf.square(batch_mean) batch_mean_vec = batch_mean batch_var_vec = batch_var beta, gamma, moving_mean, moving_var = get_bn_variables( num_chan, scale, center, beta_initializer, gamma_initializer) if new_shape is not None: batch_mean = tf.reshape(batch_mean, new_shape) batch_var = tf.reshape(batch_var, new_shape) # Using fused_batch_norm(is_training=False) is actually slightly faster, # but hopefully this call will be JITed in the future. xn = tf.nn.batch_normalization( inputs, batch_mean, batch_var, tf.reshape(beta, new_shape), tf.reshape(gamma, new_shape), epsilon) else: xn = tf.nn.batch_normalization( inputs, batch_mean, batch_var, beta, gamma, epsilon) if ctx.is_main_training_tower: ret = update_bn_ema( xn, batch_mean_vec, batch_var_vec, moving_mean, moving_var, momentum) else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder( moving_mean=moving_mean, mean=moving_mean, # for backward-compatibility moving_variance=moving_var, variance=moving_var) # for backward-compatibility if scale: vh.gamma = gamma if center: vh.beta = beta return ret
Batch Renormalization layer, as described in the paper: `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models <https://arxiv.org/abs/1702.03275>`_. This implementation is a wrapper around `tf.layers.batch_normalization`. Args: x (tf.Tensor): a NHWC or NC tensor. rmax, dmax (tf.Tensor): a scalar tensor, the maximum allowed corrections. decay (float): decay rate of moving average. epsilon (float): epsilon to avoid divide-by-zero. use_scale, use_bias (bool): whether to use the extra affine transformation or not. Returns: tf.Tensor: a tensor named ``output`` with the same shape of x. Variable Names: * ``beta``: the bias term. * ``gamma``: the scale term. Input will be transformed by ``x * gamma + beta``. * ``moving_mean, renorm_mean, renorm_mean_weight``: See TF documentation. * ``moving_variance, renorm_stddev, renorm_stddev_weight``: See TF documentation. def BatchRenorm(x, rmax, dmax, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=None, data_format='channels_last'): """ Batch Renormalization layer, as described in the paper: `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models <https://arxiv.org/abs/1702.03275>`_. This implementation is a wrapper around `tf.layers.batch_normalization`. Args: x (tf.Tensor): a NHWC or NC tensor. rmax, dmax (tf.Tensor): a scalar tensor, the maximum allowed corrections. decay (float): decay rate of moving average. epsilon (float): epsilon to avoid divide-by-zero. use_scale, use_bias (bool): whether to use the extra affine transformation or not. Returns: tf.Tensor: a tensor named ``output`` with the same shape of x. Variable Names: * ``beta``: the bias term. * ``gamma``: the scale term. Input will be transformed by ``x * gamma + beta``. * ``moving_mean, renorm_mean, renorm_mean_weight``: See TF documentation. * ``moving_variance, renorm_stddev, renorm_stddev_weight``: See TF documentation. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4] if ndims == 2: data_format = 'channels_first' ctx = get_current_tower_context() coll_bk = backup_collection([tf.GraphKeys.UPDATE_OPS]) layer = tf.layers.BatchNormalization( axis=1 if data_format == 'channels_first' else 3, momentum=momentum, epsilon=epsilon, center=center, scale=scale, renorm=True, renorm_clipping={ 'rmin': 1.0 / rmax, 'rmax': rmax, 'dmax': dmax}, renorm_momentum=0.99, gamma_initializer=gamma_initializer, fused=False, _reuse=tf.get_variable_scope().reuse) xn = layer.apply(x, training=ctx.is_training, scope=tf.get_variable_scope()) if ctx.is_main_training_tower: for v in layer.non_trainable_variables: if isinstance(v, tf.Variable): tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) else: # only run UPDATE_OPS in the first tower restore_collection(coll_bk) if ndims == 2: xn = tf.squeeze(xn, [1, 2]) ret = tf.identity(xn, name='output') # TODO not sure whether to add moving_mean/moving_var to VH now vh = ret.variables = VariableHolder() if scale: vh.gamma = layer.gamma if center: vh.beta = layer.beta return ret
return an image generated from z def generator(self, z): """ return an image generated from z""" nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2): l = Conv2DTranspose('deconv1', l, nf * 4) l = Conv2DTranspose('deconv2', l, nf * 2) l = Conv2DTranspose('deconv3', l, nf) l = Conv2DTranspose('deconv4', l, 3, activation=tf.identity) l = tf.tanh(l, name='gen') return l
return a (b, 1) logits def discriminator(self, imgs): """ return a (b, 1) logits""" nf = 64 with argscope(Conv2D, kernel_size=4, strides=2): l = (LinearWrap(imgs) .Conv2D('conv0', nf, activation=tf.nn.leaky_relu) .Conv2D('conv1', nf * 2) .BatchNorm('bn1') .tf.nn.leaky_relu() .Conv2D('conv2', nf * 4) .BatchNorm('bn2') .tf.nn.leaky_relu() .Conv2D('conv3', nf * 8) .BatchNorm('bn3') .tf.nn.leaky_relu() .FullyConnected('fct', 1)()) return l
Args: boxes: nx4 floatbox Returns: n def area(boxes): """ Args: boxes: nx4 floatbox Returns: n """ x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1) return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections def pairwise_intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections """ x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1) x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1) all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2)) all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2)) intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2)) all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2)) intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
Computes pairwise intersection-over-union between box collections. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise iou scores. def pairwise_iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = pairwise_intersection(boxlist1, boxlist2) areas1 = area(boxlist1) areas2 = area(boxlist2) unions = ( tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections) return tf.where( tf.equal(intersections, 0.0), tf.zeros_like(intersections), tf.truediv(intersections, unions))
:param path: path to the model :param start: a `str`. the starting characters :param length: a `int`. the length of text to generate def sample(path, start, length): """ :param path: path to the model :param start: a `str`. the starting characters :param length: a `int`. the length of text to generate """ # initialize vocabulary and sequence length param.seq_len = 1 ds = CharRNNData(param.corpus, 100000) pred = OfflinePredictor(PredictConfig( model=Model(), session_init=SaverRestore(path), input_names=['input', 'c0', 'h0', 'c1', 'h1'], output_names=['prob', 'last_state'])) # feed the starting sentence initial = np.zeros((1, param.rnn_size)) for c in start[:-1]: x = np.array([[ds.char2idx[c]]], dtype='int32') _, state = pred(x, initial, initial, initial, initial) def pick(prob): t = np.cumsum(prob) s = np.sum(prob) return(int(np.searchsorted(t, np.random.rand(1) * s))) # generate more ret = start c = start[-1] for k in range(length): x = np.array([[ds.char2idx[c]]], dtype='int32') prob, state = pred(x, state[0, 0], state[0, 1], state[1, 0], state[1, 1]) c = ds.chars[pick(prob[0])] ret += c print(ret)
Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_. Args: x (tf.Tensor): a NHWC or NC tensor. Channel has to be known. num_unit (int): a int. Must be divisible by C. Returns: tf.Tensor: of shape NHW(C/num_unit) named ``output``. def Maxout(x, num_unit): """ Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_. Args: x (tf.Tensor): a NHWC or NC tensor. Channel has to be known. num_unit (int): a int. Must be divisible by C. Returns: tf.Tensor: of shape NHW(C/num_unit) named ``output``. """ input_shape = x.get_shape().as_list() ndim = len(input_shape) assert ndim == 4 or ndim == 2 ch = input_shape[-1] assert ch is not None and ch % num_unit == 0 if ndim == 4: x = tf.reshape(x, [-1, input_shape[1], input_shape[2], ch / num_unit, num_unit]) else: x = tf.reshape(x, [-1, ch / num_unit, num_unit]) return tf.reduce_max(x, ndim, name='output')