repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.set_chat_description | def set_chat_description(self, chat_id, description):
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: Int... | python | def set_chat_description(self, chat_id, description):
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: Int... | [
"def",
"set_chat_description",
"(",
"self",
",",
"chat_id",
",",
"description",
")",
":",
"return",
"apihelper",
".",
"set_chat_description",
"(",
"self",
".",
"token",
",",
"chat_id",
",",
"description",
")"
] | Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: Int or Str: Unique identifier for the target chat or username of the target c... | [
"Use",
"this",
"method",
"to",
"change",
"the",
"description",
"of",
"a",
"supergroup",
"or",
"a",
"channel",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"appropr... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L957-L967 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.pin_chat_message | def pin_chat_message(self, chat_id, message_id, disable_notification=False):
"""
Use this method to pin a message in a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: In... | python | def pin_chat_message(self, chat_id, message_id, disable_notification=False):
"""
Use this method to pin a message in a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: In... | [
"def",
"pin_chat_message",
"(",
"self",
",",
"chat_id",
",",
"message_id",
",",
"disable_notification",
"=",
"False",
")",
":",
"return",
"apihelper",
".",
"pin_chat_message",
"(",
"self",
".",
"token",
",",
"chat_id",
",",
"message_id",
",",
"disable_notificati... | Use this method to pin a message in a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel
(in... | [
"Use",
"this",
"method",
"to",
"pin",
"a",
"message",
"in",
"a",
"supergroup",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"appropriate",
"admin",
"rights",
".",
... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L969-L981 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.reply_to | def reply_to(self, message, text, **kwargs):
"""
Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)`
"""
return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) | python | def reply_to(self, message, text, **kwargs):
"""
Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)`
"""
return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) | [
"def",
"reply_to",
"(",
"self",
",",
"message",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"send_message",
"(",
"message",
".",
"chat",
".",
"id",
",",
"text",
",",
"reply_to_message_id",
"=",
"message",
".",
"message_id",
"... | Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` | [
"Convenience",
"function",
"for",
"send_message",
"(",
"message",
".",
"chat",
".",
"id",
"text",
"reply_to_message_id",
"=",
"message",
".",
"message_id",
"**",
"kwargs",
")"
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1061-L1065 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.answer_inline_query | def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None,
switch_pm_text=None, switch_pm_parameter=None):
"""
Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results p... | python | def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None,
switch_pm_text=None, switch_pm_parameter=None):
"""
Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results p... | [
"def",
"answer_inline_query",
"(",
"self",
",",
"inline_query_id",
",",
"results",
",",
"cache_time",
"=",
"None",
",",
"is_personal",
"=",
"None",
",",
"next_offset",
"=",
"None",
",",
"switch_pm_text",
"=",
"None",
",",
"switch_pm_parameter",
"=",
"None",
")... | Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results per query are allowed.
:param inline_query_id: Unique identifier for the answered query
:param results: Array of results for the inline query
:param cache_time: The maximum amount of... | [
"Use",
"this",
"method",
"to",
"send",
"answers",
"to",
"an",
"inline",
"query",
".",
"On",
"success",
"True",
"is",
"returned",
".",
"No",
"more",
"than",
"50",
"results",
"per",
"query",
"are",
"allowed",
".",
":",
"param",
"inline_query_id",
":",
"Uni... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1067-L1083 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.answer_callback_query | def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to
the user as a notification at the top of the chat screen or as an alert.
... | python | def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to
the user as a notification at the top of the chat screen or as an alert.
... | [
"def",
"answer_callback_query",
"(",
"self",
",",
"callback_query_id",
",",
"text",
"=",
"None",
",",
"show_alert",
"=",
"None",
",",
"url",
"=",
"None",
",",
"cache_time",
"=",
"None",
")",
":",
"return",
"apihelper",
".",
"answer_callback_query",
"(",
"sel... | Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to
the user as a notification at the top of the chat screen or as an alert.
:param callback_query_id:
:param text:
:param show_alert:
:return: | [
"Use",
"this",
"method",
"to",
"send",
"answers",
"to",
"callback",
"queries",
"sent",
"from",
"inline",
"keyboards",
".",
"The",
"answer",
"will",
"be",
"displayed",
"to",
"the",
"user",
"as",
"a",
"notification",
"at",
"the",
"top",
"of",
"the",
"chat",
... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1085-L1094 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.get_sticker_set | def get_sticker_set(self, name):
"""
Use this method to get a sticker set. On success, a StickerSet object is returned.
:param name:
:return:
"""
result = apihelper.get_sticker_set(self.token, name)
return types.StickerSet.de_json(result) | python | def get_sticker_set(self, name):
"""
Use this method to get a sticker set. On success, a StickerSet object is returned.
:param name:
:return:
"""
result = apihelper.get_sticker_set(self.token, name)
return types.StickerSet.de_json(result) | [
"def",
"get_sticker_set",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"apihelper",
".",
"get_sticker_set",
"(",
"self",
".",
"token",
",",
"name",
")",
"return",
"types",
".",
"StickerSet",
".",
"de_json",
"(",
"result",
")"
] | Use this method to get a sticker set. On success, a StickerSet object is returned.
:param name:
:return: | [
"Use",
"this",
"method",
"to",
"get",
"a",
"sticker",
"set",
".",
"On",
"success",
"a",
"StickerSet",
"object",
"is",
"returned",
".",
":",
"param",
"name",
":",
":",
"return",
":"
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1109-L1116 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.upload_sticker_file | def upload_sticker_file(self, user_id, png_sticker):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet
methods (can be used multiple times). Returns the uploaded File on success.
:param user_id:
:param png_sticker:
... | python | def upload_sticker_file(self, user_id, png_sticker):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet
methods (can be used multiple times). Returns the uploaded File on success.
:param user_id:
:param png_sticker:
... | [
"def",
"upload_sticker_file",
"(",
"self",
",",
"user_id",
",",
"png_sticker",
")",
":",
"result",
"=",
"apihelper",
".",
"upload_sticker_file",
"(",
"self",
".",
"token",
",",
"user_id",
",",
"png_sticker",
")",
"return",
"types",
".",
"File",
".",
"de_json... | Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet
methods (can be used multiple times). Returns the uploaded File on success.
:param user_id:
:param png_sticker:
:return: | [
"Use",
"this",
"method",
"to",
"upload",
"a",
".",
"png",
"file",
"with",
"a",
"sticker",
"for",
"later",
"use",
"in",
"createNewStickerSet",
"and",
"addStickerToSet",
"methods",
"(",
"can",
"be",
"used",
"multiple",
"times",
")",
".",
"Returns",
"the",
"u... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1118-L1127 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.create_new_sticker_set | def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None,
mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Returns True on success.
... | python | def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None,
mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Returns True on success.
... | [
"def",
"create_new_sticker_set",
"(",
"self",
",",
"user_id",
",",
"name",
",",
"title",
",",
"png_sticker",
",",
"emojis",
",",
"contains_masks",
"=",
"None",
",",
"mask_position",
"=",
"None",
")",
":",
"return",
"apihelper",
".",
"create_new_sticker_set",
"... | Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Returns True on success.
:param user_id:
:param name:
:param title:
:param png_sticker:
:param emojis:
:param contains_masks:
:param mask_posit... | [
"Use",
"this",
"method",
"to",
"create",
"new",
"sticker",
"set",
"owned",
"by",
"a",
"user",
".",
"The",
"bot",
"will",
"be",
"able",
"to",
"edit",
"the",
"created",
"sticker",
"set",
".",
"Returns",
"True",
"on",
"success",
".",
":",
"param",
"user_i... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1129-L1144 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.add_sticker_to_set | def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None):
"""
Use this method to add a new sticker to a set created by the bot. Returns True on success.
:param user_id:
:param name:
:param png_sticker:
:param emojis:
:param mask_positio... | python | def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None):
"""
Use this method to add a new sticker to a set created by the bot. Returns True on success.
:param user_id:
:param name:
:param png_sticker:
:param emojis:
:param mask_positio... | [
"def",
"add_sticker_to_set",
"(",
"self",
",",
"user_id",
",",
"name",
",",
"png_sticker",
",",
"emojis",
",",
"mask_position",
"=",
"None",
")",
":",
"return",
"apihelper",
".",
"add_sticker_to_set",
"(",
"self",
".",
"token",
",",
"user_id",
",",
"name",
... | Use this method to add a new sticker to a set created by the bot. Returns True on success.
:param user_id:
:param name:
:param png_sticker:
:param emojis:
:param mask_position:
:return: | [
"Use",
"this",
"method",
"to",
"add",
"a",
"new",
"sticker",
"to",
"a",
"set",
"created",
"by",
"the",
"bot",
".",
"Returns",
"True",
"on",
"success",
".",
":",
"param",
"user_id",
":",
":",
"param",
"name",
":",
":",
"param",
"png_sticker",
":",
":"... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1146-L1156 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.set_sticker_position_in_set | def set_sticker_position_in_set(self, sticker, position):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
:param sticker:
:param position:
:return:
"""
return apihelper.set_sticker_position_in_set... | python | def set_sticker_position_in_set(self, sticker, position):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
:param sticker:
:param position:
:return:
"""
return apihelper.set_sticker_position_in_set... | [
"def",
"set_sticker_position_in_set",
"(",
"self",
",",
"sticker",
",",
"position",
")",
":",
"return",
"apihelper",
".",
"set_sticker_position_in_set",
"(",
"self",
".",
"token",
",",
"sticker",
",",
"position",
")"
] | Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
:param sticker:
:param position:
:return: | [
"Use",
"this",
"method",
"to",
"move",
"a",
"sticker",
"in",
"a",
"set",
"created",
"by",
"the",
"bot",
"to",
"a",
"specific",
"position",
".",
"Returns",
"True",
"on",
"success",
".",
":",
"param",
"sticker",
":",
":",
"param",
"position",
":",
":",
... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1158-L1165 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.register_for_reply | def register_for_reply(self, message, callback, *args, **kwargs):
"""
Registers a callback function to be notified when a reply to `message` arrives.
Warning: In case `callback` as lambda function, saving reply handlers will not work.
:param message: The message for which we are aw... | python | def register_for_reply(self, message, callback, *args, **kwargs):
"""
Registers a callback function to be notified when a reply to `message` arrives.
Warning: In case `callback` as lambda function, saving reply handlers will not work.
:param message: The message for which we are aw... | [
"def",
"register_for_reply",
"(",
"self",
",",
"message",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message_id",
"=",
"message",
".",
"message_id",
"self",
".",
"register_for_reply_by_message_id",
"(",
"message_id",
",",
"callback"... | Registers a callback function to be notified when a reply to `message` arrives.
Warning: In case `callback` as lambda function, saving reply handlers will not work.
:param message: The message for which we are awaiting a reply.
:param callback: The callback function to be called when a ... | [
"Registers",
"a",
"callback",
"function",
"to",
"be",
"notified",
"when",
"a",
"reply",
"to",
"message",
"arrives",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1175-L1186 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.register_for_reply_by_message_id | def register_for_reply_by_message_id(self, message_id, callback, *args, **kwargs):
"""
Registers a callback function to be notified when a reply to `message` arrives.
Warning: In case `callback` as lambda function, saving reply handlers will not work.
:param message_id: The id of the ... | python | def register_for_reply_by_message_id(self, message_id, callback, *args, **kwargs):
"""
Registers a callback function to be notified when a reply to `message` arrives.
Warning: In case `callback` as lambda function, saving reply handlers will not work.
:param message_id: The id of the ... | [
"def",
"register_for_reply_by_message_id",
"(",
"self",
",",
"message_id",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"message_id",
"in",
"self",
".",
"reply_handlers",
".",
"keys",
"(",
")",
":",
"self",
".",
"reply_handle... | Registers a callback function to be notified when a reply to `message` arrives.
Warning: In case `callback` as lambda function, saving reply handlers will not work.
:param message_id: The id of the message for which we are awaiting a reply.
:param callback: The callback function to be call... | [
"Registers",
"a",
"callback",
"function",
"to",
"be",
"notified",
"when",
"a",
"reply",
"to",
"message",
"arrives",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1188-L1203 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.register_next_step_handler | def register_next_step_handler(self, message, callback, *args, **kwargs):
"""
Registers a callback function to be notified when new message arrives after `message`.
Warning: In case `callback` as lambda function, saving next step handlers will not work.
:param message: The message ... | python | def register_next_step_handler(self, message, callback, *args, **kwargs):
"""
Registers a callback function to be notified when new message arrives after `message`.
Warning: In case `callback` as lambda function, saving next step handlers will not work.
:param message: The message ... | [
"def",
"register_next_step_handler",
"(",
"self",
",",
"message",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"chat_id",
"=",
"message",
".",
"chat",
".",
"id",
"self",
".",
"register_next_step_handler_by_chat_id",
"(",
"chat_id",
"... | Registers a callback function to be notified when new message arrives after `message`.
Warning: In case `callback` as lambda function, saving next step handlers will not work.
:param message: The message for which we want to handle new message in the same chat.
:param callback: The call... | [
"Registers",
"a",
"callback",
"function",
"to",
"be",
"notified",
"when",
"new",
"message",
"arrives",
"after",
"message",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1217-L1229 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.register_next_step_handler_by_chat_id | def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs):
"""
Registers a callback function to be notified when new message arrives after `message`.
Warning: In case `callback` as lambda function, saving next step handlers will not work.
:param chat_id: T... | python | def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs):
"""
Registers a callback function to be notified when new message arrives after `message`.
Warning: In case `callback` as lambda function, saving next step handlers will not work.
:param chat_id: T... | [
"def",
"register_next_step_handler_by_chat_id",
"(",
"self",
",",
"chat_id",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"chat_id",
"in",
"self",
".",
"next_step_handlers",
".",
"keys",
"(",
")",
":",
"self",
".",
"next_step... | Registers a callback function to be notified when new message arrives after `message`.
Warning: In case `callback` as lambda function, saving next step handlers will not work.
:param chat_id: The chat for which we want to handle new message.
:param callback: The callback function which ... | [
"Registers",
"a",
"callback",
"function",
"to",
"be",
"notified",
"when",
"new",
"message",
"arrives",
"after",
"message",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1231-L1248 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.clear_step_handler | def clear_step_handler(self, message):
"""
Clears all callback functions registered by register_next_step_handler().
:param message: The message for which we want to handle new message after that in same chat.
"""
chat_id = message.chat.id
self.clear_step_handler_by_... | python | def clear_step_handler(self, message):
"""
Clears all callback functions registered by register_next_step_handler().
:param message: The message for which we want to handle new message after that in same chat.
"""
chat_id = message.chat.id
self.clear_step_handler_by_... | [
"def",
"clear_step_handler",
"(",
"self",
",",
"message",
")",
":",
"chat_id",
"=",
"message",
".",
"chat",
".",
"id",
"self",
".",
"clear_step_handler_by_chat_id",
"(",
"chat_id",
")"
] | Clears all callback functions registered by register_next_step_handler().
:param message: The message for which we want to handle new message after that in same chat. | [
"Clears",
"all",
"callback",
"functions",
"registered",
"by",
"register_next_step_handler",
"()",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1250-L1257 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.clear_step_handler_by_chat_id | def clear_step_handler_by_chat_id(self, chat_id):
"""
Clears all callback functions registered by register_next_step_handler().
:param chat_id: The chat for which we want to clear next step handlers
"""
self.next_step_handlers[chat_id] = []
if self.next_step_saver is no... | python | def clear_step_handler_by_chat_id(self, chat_id):
"""
Clears all callback functions registered by register_next_step_handler().
:param chat_id: The chat for which we want to clear next step handlers
"""
self.next_step_handlers[chat_id] = []
if self.next_step_saver is no... | [
"def",
"clear_step_handler_by_chat_id",
"(",
"self",
",",
"chat_id",
")",
":",
"self",
".",
"next_step_handlers",
"[",
"chat_id",
"]",
"=",
"[",
"]",
"if",
"self",
".",
"next_step_saver",
"is",
"not",
"None",
":",
"self",
".",
"next_step_saver",
".",
"start_... | Clears all callback functions registered by register_next_step_handler().
:param chat_id: The chat for which we want to clear next step handlers | [
"Clears",
"all",
"callback",
"functions",
"registered",
"by",
"register_next_step_handler",
"()",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1259-L1268 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.clear_reply_handlers_by_message_id | def clear_reply_handlers_by_message_id(self, message_id):
"""
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers
"""
self.reply_handlers[message_id] ... | python | def clear_reply_handlers_by_message_id(self, message_id):
"""
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers
"""
self.reply_handlers[message_id] ... | [
"def",
"clear_reply_handlers_by_message_id",
"(",
"self",
",",
"message_id",
")",
":",
"self",
".",
"reply_handlers",
"[",
"message_id",
"]",
"=",
"[",
"]",
"if",
"self",
".",
"reply_saver",
"is",
"not",
"None",
":",
"self",
".",
"reply_saver",
".",
"start_s... | Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers | [
"Clears",
"all",
"callback",
"functions",
"registered",
"by",
"register_for_reply",
"()",
"and",
"register_for_reply_by_message_id",
"()",
"."
] | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1279-L1288 | train |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | TeleBot.message_handler | def message_handler(self, commands=None, regexp=None, func=None, content_types=['text'], **kwargs):
"""
Message handler decorator.
This decorator can be used to decorate functions that must handle certain types of messages.
All message handlers are tested in the order they were added.
... | python | def message_handler(self, commands=None, regexp=None, func=None, content_types=['text'], **kwargs):
"""
Message handler decorator.
This decorator can be used to decorate functions that must handle certain types of messages.
All message handlers are tested in the order they were added.
... | [
"def",
"message_handler",
"(",
"self",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"func",
"=",
"None",
",",
"content_types",
"=",
"[",
"'text'",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"handler",
")",
":",... | Message handler decorator.
This decorator can be used to decorate functions that must handle certain types of messages.
All message handlers are tested in the order they were added.
Example:
bot = TeleBot('TOKEN')
# Handles all messages which text matches regexp.
@bot.... | [
"Message",
"handler",
"decorator",
".",
"This",
"decorator",
"can",
"be",
"used",
"to",
"decorate",
"functions",
"that",
"must",
"handle",
"certain",
"types",
"of",
"messages",
".",
"All",
"message",
"handlers",
"are",
"tested",
"in",
"the",
"order",
"they",
... | 47b53b88123097f1b9562a6cd5d4e080b86185d1 | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L1315-L1357 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | generate_code | def generate_code(max_length, max_nest, ops):
"""Generates code samples.
Args:
max_length: int. max literal length.
max_nest: int. max nesting level.
ops: CodeOp. set of allowable operations.
Returns:
1. (str) output value.
2. (str) Code operation.
"""
stack = []
def fetch_one():
... | python | def generate_code(max_length, max_nest, ops):
"""Generates code samples.
Args:
max_length: int. max literal length.
max_nest: int. max nesting level.
ops: CodeOp. set of allowable operations.
Returns:
1. (str) output value.
2. (str) Code operation.
"""
stack = []
def fetch_one():
... | [
"def",
"generate_code",
"(",
"max_length",
",",
"max_nest",
",",
"ops",
")",
":",
"stack",
"=",
"[",
"]",
"def",
"fetch_one",
"(",
")",
":",
"# Always use an existing nested value for one of the operands.",
"if",
"stack",
":",
"return",
"stack",
".",
"pop",
"(",... | Generates code samples.
Args:
max_length: int. max literal length.
max_nest: int. max nesting level.
ops: CodeOp. set of allowable operations.
Returns:
1. (str) output value.
2. (str) Code operation. | [
"Generates",
"code",
"samples",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L539-L577 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | get_tokens | def get_tokens(max_value):
"""Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary.
"""
vocab = [str(i) for i in range(max_value)]
vocab = set(vocab)
vocab.update(CodeOp.LITERALS)
vocab.update(CodeOp.KEYWORDS)
vocab |= set("".... | python | def get_tokens(max_value):
"""Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary.
"""
vocab = [str(i) for i in range(max_value)]
vocab = set(vocab)
vocab.update(CodeOp.LITERALS)
vocab.update(CodeOp.KEYWORDS)
vocab |= set("".... | [
"def",
"get_tokens",
"(",
"max_value",
")",
":",
"vocab",
"=",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"max_value",
")",
"]",
"vocab",
"=",
"set",
"(",
"vocab",
")",
"vocab",
".",
"update",
"(",
"CodeOp",
".",
"LITERALS",
")",
... | Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary. | [
"Defines",
"tokens",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L580-L594 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | LearnToExecute | def LearnToExecute( # pylint: disable=invalid-name
batch_size, max_length=1, max_nesting=1, token_by_char=True,
mode=Mode.TRAIN_COMBINE, loss_threshold=0.1,
min_tries=DEFAULT_MIN_CURRICULUM_EVAL_TRIES, task_type=TaskType.ALG_CTRL):
"""Factory method for LearnToExecute Dataset module.
Args:
batch_... | python | def LearnToExecute( # pylint: disable=invalid-name
batch_size, max_length=1, max_nesting=1, token_by_char=True,
mode=Mode.TRAIN_COMBINE, loss_threshold=0.1,
min_tries=DEFAULT_MIN_CURRICULUM_EVAL_TRIES, task_type=TaskType.ALG_CTRL):
"""Factory method for LearnToExecute Dataset module.
Args:
batch_... | [
"def",
"LearnToExecute",
"(",
"# pylint: disable=invalid-name",
"batch_size",
",",
"max_length",
"=",
"1",
",",
"max_nesting",
"=",
"1",
",",
"token_by_char",
"=",
"True",
",",
"mode",
"=",
"Mode",
".",
"TRAIN_COMBINE",
",",
"loss_threshold",
"=",
"0.1",
",",
... | Factory method for LearnToExecute Dataset module.
Args:
batch_size: (int). The number of elements in a mini-batch.
max_length: (int). Maximum character length.
max_nesting: (int). Maximum level of statement nesting.
token_by_char: (bool). Tokenize by character or words?
mode: (string). Either 'tr... | [
"Factory",
"method",
"for",
"LearnToExecute",
"Dataset",
"module",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L994-L1043 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | MixCurriculum.fetch | def fetch(self):
"""Samples up to maximum difficulty."""
length = np.random.randint(1, self._max_length + 1)
nesting = np.random.randint(1, self._max_length + 1)
return length, nesting | python | def fetch(self):
"""Samples up to maximum difficulty."""
length = np.random.randint(1, self._max_length + 1)
nesting = np.random.randint(1, self._max_length + 1)
return length, nesting | [
"def",
"fetch",
"(",
"self",
")",
":",
"length",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"self",
".",
"_max_length",
"+",
"1",
")",
"nesting",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"self",
".",
"_max_length",
"... | Samples up to maximum difficulty. | [
"Samples",
"up",
"to",
"maximum",
"difficulty",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L234-L238 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | CombineCurriculum.update | def update(self, loss, force=False):
"""Increments level difficulty (length and nesting) by 1 until maximum."""
do_update = super(CombineCurriculum, self).update(loss, force)
if not do_update:
return False
if self._curr_length < self._max_length:
self._curr_length += 1
elif self._curr_n... | python | def update(self, loss, force=False):
"""Increments level difficulty (length and nesting) by 1 until maximum."""
do_update = super(CombineCurriculum, self).update(loss, force)
if not do_update:
return False
if self._curr_length < self._max_length:
self._curr_length += 1
elif self._curr_n... | [
"def",
"update",
"(",
"self",
",",
"loss",
",",
"force",
"=",
"False",
")",
":",
"do_update",
"=",
"super",
"(",
"CombineCurriculum",
",",
"self",
")",
".",
"update",
"(",
"loss",
",",
"force",
")",
"if",
"not",
"do_update",
":",
"return",
"False",
"... | Increments level difficulty (length and nesting) by 1 until maximum. | [
"Increments",
"level",
"difficulty",
"(",
"length",
"and",
"nesting",
")",
"by",
"1",
"until",
"maximum",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L255-L271 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | CombineCurriculum.fetch | def fetch(self):
"""Samples up to current difficulty."""
length = np.random.randint(1, self._curr_length + 1)
nesting = np.random.randint(1, self._curr_nesting + 1)
return length, nesting | python | def fetch(self):
"""Samples up to current difficulty."""
length = np.random.randint(1, self._curr_length + 1)
nesting = np.random.randint(1, self._curr_nesting + 1)
return length, nesting | [
"def",
"fetch",
"(",
"self",
")",
":",
"length",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"self",
".",
"_curr_length",
"+",
"1",
")",
"nesting",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"self",
".",
"_curr_nesting",
... | Samples up to current difficulty. | [
"Samples",
"up",
"to",
"current",
"difficulty",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L273-L277 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | TokenDataSource.generate_flat_data | def generate_flat_data(self):
"""Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required.
"""
# Construct the string statements.
all_statements = []
all_targets = []
self.sequence_sizes_in = []
self.sequence_sizes_out = []
for... | python | def generate_flat_data(self):
"""Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required.
"""
# Construct the string statements.
all_statements = []
all_targets = []
self.sequence_sizes_in = []
self.sequence_sizes_out = []
for... | [
"def",
"generate_flat_data",
"(",
"self",
")",
":",
"# Construct the string statements.",
"all_statements",
"=",
"[",
"]",
"all_targets",
"=",
"[",
"]",
"self",
".",
"sequence_sizes_in",
"=",
"[",
"]",
"self",
".",
"sequence_sizes_out",
"=",
"[",
"]",
"for",
"... | Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required. | [
"Generates",
"batched",
"data",
"in",
"flat",
"numpy",
"arrays",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L656-L699 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | TokenDataSource.tokenize | def tokenize(self, char_input, max_len, by_char=False):
"""Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
... | python | def tokenize(self, char_input, max_len, by_char=False):
"""Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
... | [
"def",
"tokenize",
"(",
"self",
",",
"char_input",
",",
"max_len",
",",
"by_char",
"=",
"False",
")",
":",
"if",
"by_char",
":",
"tokenized_list",
"=",
"[",
"self",
".",
"_vocab_dict",
"[",
"token",
"]",
"for",
"token",
"in",
"char_input",
"]",
"else",
... | Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
groupings are tokens.
Returns:
A padded list of st... | [
"Produces",
"the",
"list",
"of",
"integer",
"indices",
"corresponding",
"to",
"a",
"token",
"list",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L701-L747 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | LearnToExecuteState.get_task_ops | def get_task_ops(task_type=TaskType.ALG_CTRL):
"""Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops.
"""
try:
return LearnToExecuteState.TASK_TYPE_OPS[task_type]
except KeyError:
... | python | def get_task_ops(task_type=TaskType.ALG_CTRL):
"""Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops.
"""
try:
return LearnToExecuteState.TASK_TYPE_OPS[task_type]
except KeyError:
... | [
"def",
"get_task_ops",
"(",
"task_type",
"=",
"TaskType",
".",
"ALG_CTRL",
")",
":",
"try",
":",
"return",
"LearnToExecuteState",
".",
"TASK_TYPE_OPS",
"[",
"task_type",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Bad task_type '%s', check config.\"... | Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops. | [
"Returns",
"an",
"operations",
"list",
"based",
"on",
"the",
"specified",
"task",
"index",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L863-L875 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | LearnToExecuteState.make_batch | def make_batch(self):
"""Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
... | python | def make_batch(self):
"""Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
... | [
"def",
"make_batch",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"reset_data_source",
"(",
")",
"obs",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_data_source",
".",
"flat_data",
",",
"[",
"self",
".",
"batch_size",
",",
"-",
"1",
"]... | Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
4. batch size tensor c... | [
"Generator",
"function",
"for",
"batchifying",
"data",
"for",
"learning",
"to",
"execute",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L932-L957 | train |
deepmind/sonnet | sonnet/examples/learn_to_execute.py | LearnToExecuteState.to_human_readable | def to_human_readable(self, data, label_batch_entries=True, indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one ho... | python | def to_human_readable(self, data, label_batch_entries=True, indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one ho... | [
"def",
"to_human_readable",
"(",
"self",
",",
"data",
",",
"label_batch_entries",
"=",
"True",
",",
"indices",
"=",
"None",
",",
"sep",
"=",
"\"\\n\"",
")",
":",
"batch_size",
"=",
"data",
".",
"shape",
"[",
"1",
"]",
"result",
"=",
"[",
"]",
"indices"... | Returns a human-readable version of a one-hot encoding of words.
Args:
data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one hot dimensionality.
label_batch_entries: (bool). Whether to add numerical label before each
batch elem... | [
"Returns",
"a",
"human",
"-",
"readable",
"version",
"of",
"a",
"one",
"-",
"hot",
"encoding",
"of",
"words",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L959-L983 | train |
deepmind/sonnet | sonnet/python/modules/batch_norm.py | BatchNorm._infer_fused_data_format | def _infer_fused_data_format(self, input_batch):
"""Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: ... | python | def _infer_fused_data_format(self, input_batch):
"""Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: ... | [
"def",
"_infer_fused_data_format",
"(",
"self",
",",
"input_batch",
")",
":",
"input_shape",
"=",
"input_batch",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"input_shape_len",
"=",
"len",
"(",
"input_shape",
")",
"if",
"input_shape_len",
"!=",
"4",
... | Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: A Tensor of arbitrary dimension.
Returns:
A s... | [
"Infers",
"the",
"data",
"format",
"for",
"the",
"fused",
"batch",
"norm",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L325-L359 | train |
deepmind/sonnet | sonnet/python/modules/batch_norm.py | BatchNorm._fused_batch_norm_op | def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_shape = mean.get_shape()
variance_shape = variance.get_shape()
# The fused batch norm expects the mean, variance, gamm... | python | def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_shape = mean.get_shape()
variance_shape = variance.get_shape()
# The fused batch norm expects the mean, variance, gamm... | [
"def",
"_fused_batch_norm_op",
"(",
"self",
",",
"input_batch",
",",
"mean",
",",
"variance",
",",
"use_batch_stats",
")",
":",
"# Store the original shape of the mean and variance.",
"mean_shape",
"=",
"mean",
".",
"get_shape",
"(",
")",
"variance_shape",
"=",
"varia... | Creates a fused batch normalization op. | [
"Creates",
"a",
"fused",
"batch",
"normalization",
"op",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L361-L398 | train |
deepmind/sonnet | sonnet/python/modules/batch_norm.py | BatchNorm._batch_norm_op | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... | python | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... | [
"def",
"_batch_norm_op",
"(",
"self",
",",
"input_batch",
",",
"mean",
",",
"variance",
",",
"use_batch_stats",
",",
"stat_dtype",
")",
":",
"if",
"self",
".",
"_fused",
":",
"# For the non-training case where not using batch stats,",
"# pass in the moving statistic varia... | Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Tensor of arbitrary dimension.
mean: A mean tensor, of the same dtype as `input_batch`.
variance: A var... | [
"Creates",
"a",
"batch",
"normalization",
"op",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L400-L442 | train |
deepmind/sonnet | sonnet/python/modules/batch_norm.py | BatchNorm._build_scale_offset | def _build_scale_offset(self, dtype):
"""Sets up optional scale and offset factors."""
# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.
if self._fused and dtype == tf.float16:
dtype = tf.float32
# The fused batch norm operation needs the beta, gamma variables,
# so ... | python | def _build_scale_offset(self, dtype):
"""Sets up optional scale and offset factors."""
# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.
if self._fused and dtype == tf.float16:
dtype = tf.float32
# The fused batch norm operation needs the beta, gamma variables,
# so ... | [
"def",
"_build_scale_offset",
"(",
"self",
",",
"dtype",
")",
":",
"# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.",
"if",
"self",
".",
"_fused",
"and",
"dtype",
"==",
"tf",
".",
"float16",
":",
"dtype",
"=",
"tf",
".",
"float32",
"# The ... | Sets up optional scale and offset factors. | [
"Sets",
"up",
"optional",
"scale",
"and",
"offset",
"factors",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L444-L478 | train |
deepmind/sonnet | sonnet/python/modules/batch_norm.py | BatchNorm._build | def _build(self, input_batch, is_training, test_local_stats=True):
"""Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indi... | python | def _build(self, input_batch, is_training, test_local_stats=True):
"""Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indi... | [
"def",
"_build",
"(",
"self",
",",
"input_batch",
",",
"is_training",
",",
"test_local_stats",
"=",
"True",
")",
":",
"input_shape",
"=",
"input_batch",
".",
"get_shape",
"(",
")",
"if",
"self",
".",
"_axis",
"is",
"not",
"None",
":",
"if",
"len",
"(",
... | Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indicate if the module should be connected in
training mode, meaning t... | [
"Connects",
"the",
"BatchNorm",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L480-L557 | train |
deepmind/sonnet | sonnet/examples/dataset_shakespeare.py | TokenDataSource.tokenize | def tokenize(self, token_list):
"""Produces the list of integer indices corresponding to a token list."""
return [
self._vocab_dict.get(token, self._vocab_dict[self.UNK])
for token in token_list
] | python | def tokenize(self, token_list):
"""Produces the list of integer indices corresponding to a token list."""
return [
self._vocab_dict.get(token, self._vocab_dict[self.UNK])
for token in token_list
] | [
"def",
"tokenize",
"(",
"self",
",",
"token_list",
")",
":",
"return",
"[",
"self",
".",
"_vocab_dict",
".",
"get",
"(",
"token",
",",
"self",
".",
"_vocab_dict",
"[",
"self",
".",
"UNK",
"]",
")",
"for",
"token",
"in",
"token_list",
"]"
] | Produces the list of integer indices corresponding to a token list. | [
"Produces",
"the",
"list",
"of",
"integer",
"indices",
"corresponding",
"to",
"a",
"token",
"list",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L81-L86 | train |
deepmind/sonnet | sonnet/examples/dataset_shakespeare.py | TinyShakespeareDataset._get_batch | def _get_batch(self):
"""Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch]
"""
batch_indices = np.mod(
np.array([
np.arange(head_index, head_index + self._num_steps + 1) for
head_inde... | python | def _get_batch(self):
"""Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch]
"""
batch_indices = np.mod(
np.array([
np.arange(head_index, head_index + self._num_steps + 1) for
head_inde... | [
"def",
"_get_batch",
"(",
"self",
")",
":",
"batch_indices",
"=",
"np",
".",
"mod",
"(",
"np",
".",
"array",
"(",
"[",
"np",
".",
"arange",
"(",
"head_index",
",",
"head_index",
"+",
"self",
".",
"_num_steps",
"+",
"1",
")",
"for",
"head_index",
"in"... | Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch] | [
"Returns",
"a",
"batch",
"of",
"sequences",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L156-L181 | train |
deepmind/sonnet | sonnet/examples/dataset_shakespeare.py | TinyShakespeareDataset._build | def _build(self):
"""Returns a tuple containing observation and target one-hot tensors."""
q = tf.FIFOQueue(
self._queue_capacity, [self._dtype, self._dtype],
shapes=[[self._num_steps, self._batch_size, self._vocab_size]]*2)
obs, target = tf.py_func(self._get_batch, [], [tf.int32, tf.int32])... | python | def _build(self):
"""Returns a tuple containing observation and target one-hot tensors."""
q = tf.FIFOQueue(
self._queue_capacity, [self._dtype, self._dtype],
shapes=[[self._num_steps, self._batch_size, self._vocab_size]]*2)
obs, target = tf.py_func(self._get_batch, [], [tf.int32, tf.int32])... | [
"def",
"_build",
"(",
"self",
")",
":",
"q",
"=",
"tf",
".",
"FIFOQueue",
"(",
"self",
".",
"_queue_capacity",
",",
"[",
"self",
".",
"_dtype",
",",
"self",
".",
"_dtype",
"]",
",",
"shapes",
"=",
"[",
"[",
"self",
".",
"_num_steps",
",",
"self",
... | Returns a tuple containing observation and target one-hot tensors. | [
"Returns",
"a",
"tuple",
"containing",
"observation",
"and",
"target",
"one",
"-",
"hot",
"tensors",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L183-L194 | train |
deepmind/sonnet | sonnet/examples/dataset_shakespeare.py | TinyShakespeareDataset.cost | def cost(self, logits, target):
"""Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
"""
logits = tf.reshape(logi... | python | def cost(self, logits, target):
"""Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
"""
logits = tf.reshape(logi... | [
"def",
"cost",
"(",
"self",
",",
"logits",
",",
"target",
")",
":",
"logits",
"=",
"tf",
".",
"reshape",
"(",
"logits",
",",
"[",
"self",
".",
"_num_steps",
"*",
"self",
".",
"_batch_size",
",",
"-",
"1",
"]",
")",
"target",
"=",
"tf",
".",
"resh... | Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time. | [
"Returns",
"cost",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L196-L212 | train |
deepmind/sonnet | sonnet/examples/dataset_shakespeare.py | TinyShakespeareDataset.to_human_readable | def to_human_readable(self,
data,
label_batch_entries=True,
indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: A tuple with (obs, target). `obs` is a numpy... | python | def to_human_readable(self,
data,
label_batch_entries=True,
indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: A tuple with (obs, target). `obs` is a numpy... | [
"def",
"to_human_readable",
"(",
"self",
",",
"data",
",",
"label_batch_entries",
"=",
"True",
",",
"indices",
"=",
"None",
",",
"sep",
"=",
"\"\\n\"",
")",
":",
"obs",
"=",
"data",
"[",
"0",
"]",
"batch_size",
"=",
"obs",
".",
"shape",
"[",
"1",
"]"... | Returns a human-readable version of a one-hot encoding of words.
Args:
data: A tuple with (obs, target). `obs` is a numpy array with one-hot
encoding of words.
label_batch_entries: bool. Whether to add numerical label before each
batch element in the output string.
indices: Li... | [
"Returns",
"a",
"human",
"-",
"readable",
"version",
"of",
"a",
"one",
"-",
"hot",
"encoding",
"of",
"words",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L214-L242 | train |
deepmind/sonnet | sonnet/examples/dataset_mnist_cifar10.py | get_data | def get_data(name, train_batch_size, test_batch_size):
"""Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:... | python | def get_data(name, train_batch_size, test_batch_size):
"""Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:... | [
"def",
"get_data",
"(",
"name",
",",
"train_batch_size",
",",
"test_batch_size",
")",
":",
"if",
"name",
"not",
"in",
"[",
"'mnist'",
",",
"'cifar10'",
"]",
":",
"raise",
"ValueError",
"(",
"'Expected dataset \\'mnist\\' or \\'cifar10\\', but got %s'",
"%",
"name",
... | Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:
train_iterator: A tf.data.Iterator, over training dat... | [
"Gets",
"training",
"and",
"testing",
"dataset",
"iterators",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_mnist_cifar10.py#L34-L87 | train |
deepmind/sonnet | sonnet/python/modules/util.py | get_variable_scope_name | def get_variable_scope_name(value):
"""Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueErro... | python | def get_variable_scope_name(value):
"""Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueErro... | [
"def",
"get_variable_scope_name",
"(",
"value",
")",
":",
"# If the object has a \"variable_scope\" property, use it.",
"value",
"=",
"getattr",
"(",
"value",
",",
"\"variable_scope\"",
",",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"tf",
".",
"VariableScop... | Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueError: If `value` does not identify a variabl... | [
"Returns",
"the",
"name",
"of",
"the",
"variable",
"scope",
"indicated",
"by",
"the",
"given",
"value",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L38-L58 | train |
deepmind/sonnet | sonnet/python/modules/util.py | get_variables_in_scope | def get_variables_in_scope(scope, collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns a tuple `tf.Variable`s in a scope for a given collection.
Args:
scope: `tf.VariableScope` or string to retrieve variables from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.TR... | python | def get_variables_in_scope(scope, collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns a tuple `tf.Variable`s in a scope for a given collection.
Args:
scope: `tf.VariableScope` or string to retrieve variables from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.TR... | [
"def",
"get_variables_in_scope",
"(",
"scope",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
":",
"scope_name",
"=",
"get_variable_scope_name",
"(",
"scope",
")",
"if",
"scope_name",
":",
"# Escape the name in case it contains any \".\... | Returns a tuple `tf.Variable`s in a scope for a given collection.
Args:
scope: `tf.VariableScope` or string to retrieve variables from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.TRAINABLE_VARIABLES`, which doesn't include non-trainable
variables such as mov... | [
"Returns",
"a",
"tuple",
"tf",
".",
"Variable",
"s",
"in",
"a",
"scope",
"for",
"a",
"given",
"collection",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L61-L81 | train |
deepmind/sonnet | sonnet/python/modules/util.py | get_variables_in_module | def get_variables_in_module(module,
collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns tuple of `tf.Variable`s declared inside an `snt.Module`.
Note that this operates by searching the variable scope a module contains,
and so does not know about any modules which were constructe... | python | def get_variables_in_module(module,
collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns tuple of `tf.Variable`s declared inside an `snt.Module`.
Note that this operates by searching the variable scope a module contains,
and so does not know about any modules which were constructe... | [
"def",
"get_variables_in_module",
"(",
"module",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
":",
"return",
"module",
".",
"get_variables",
"(",
"collection",
"=",
"collection",
")"
] | Returns tuple of `tf.Variable`s declared inside an `snt.Module`.
Note that this operates by searching the variable scope a module contains,
and so does not know about any modules which were constructed elsewhere but
used inside this module.
Args:
module: `snt.Module` instance to query the scope of.
co... | [
"Returns",
"tuple",
"of",
"tf",
".",
"Variable",
"s",
"declared",
"inside",
"an",
"snt",
".",
"Module",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L84-L104 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _check_nested_callables | def _check_nested_callables(dictionary, object_name):
"""Checks if all items in the dictionary and in subdictionaries are callables.
Args:
dictionary: Dictionary of callables or other dictionaries with callables.
object_name: The name of the object that is expected in the dictionary.
E.g. 'Initialize... | python | def _check_nested_callables(dictionary, object_name):
"""Checks if all items in the dictionary and in subdictionaries are callables.
Args:
dictionary: Dictionary of callables or other dictionaries with callables.
object_name: The name of the object that is expected in the dictionary.
E.g. 'Initialize... | [
"def",
"_check_nested_callables",
"(",
"dictionary",
",",
"object_name",
")",
":",
"for",
"key",
",",
"entry",
"in",
"six",
".",
"iteritems",
"(",
"dictionary",
")",
":",
"if",
"hasattr",
"(",
"entry",
",",
"\"items\"",
")",
":",
"_check_nested_callables",
"... | Checks if all items in the dictionary and in subdictionaries are callables.
Args:
dictionary: Dictionary of callables or other dictionaries with callables.
object_name: The name of the object that is expected in the dictionary.
E.g. 'Initializer', 'Partitioner' or 'Regularizer'. The first letter
... | [
"Checks",
"if",
"all",
"items",
"in",
"the",
"dictionary",
"and",
"in",
"subdictionaries",
"are",
"callables",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L107-L126 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _assert_is_dictlike | def _assert_is_dictlike(maybe_dictlike, valid_keys):
"""Raises a TypeError iff `maybe_dictlike` is not a dictlike object."""
# This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc. The previous error message was quite
# opaque, this should be much clear... | python | def _assert_is_dictlike(maybe_dictlike, valid_keys):
"""Raises a TypeError iff `maybe_dictlike` is not a dictlike object."""
# This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc. The previous error message was quite
# opaque, this should be much clear... | [
"def",
"_assert_is_dictlike",
"(",
"maybe_dictlike",
",",
"valid_keys",
")",
":",
"# This covers a common mistake when people use incorrect dictionary nesting",
"# for initializers / partitioners etc. The previous error message was quite",
"# opaque, this should be much clearer.",
"if",
"not... | Raises a TypeError iff `maybe_dictlike` is not a dictlike object. | [
"Raises",
"a",
"TypeError",
"iff",
"maybe_dictlike",
"is",
"not",
"a",
"dictlike",
"object",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L129-L137 | train |
deepmind/sonnet | sonnet/python/modules/util.py | check_initializers | def check_initializers(initializers, keys):
"""Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to module... | python | def check_initializers(initializers, keys):
"""Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to module... | [
"def",
"check_initializers",
"(",
"initializers",
",",
"keys",
")",
":",
"if",
"initializers",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"initializers",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if... | Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to modules inside modules) that must satisfy the same cons... | [
"Checks",
"the",
"given",
"initializers",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L140-L178 | train |
deepmind/sonnet | sonnet/python/modules/util.py | check_partitioners | def check_partitioners(partitioners, keys):
"""Checks the given partitioners.
This checks that `partitioners` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `partitioners` are functions or
further dictionaries (the latter used, for example, in passing partitioners
to module... | python | def check_partitioners(partitioners, keys):
"""Checks the given partitioners.
This checks that `partitioners` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `partitioners` are functions or
further dictionaries (the latter used, for example, in passing partitioners
to module... | [
"def",
"check_partitioners",
"(",
"partitioners",
",",
"keys",
")",
":",
"if",
"partitioners",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"partitioners",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if... | Checks the given partitioners.
This checks that `partitioners` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `partitioners` are functions or
further dictionaries (the latter used, for example, in passing partitioners
to modules inside modules) that must satisfy the same cons... | [
"Checks",
"the",
"given",
"partitioners",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L181-L219 | train |
deepmind/sonnet | sonnet/python/modules/util.py | check_regularizers | def check_regularizers(regularizers, keys):
"""Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to module... | python | def check_regularizers(regularizers, keys):
"""Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to module... | [
"def",
"check_regularizers",
"(",
"regularizers",
",",
"keys",
")",
":",
"if",
"regularizers",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"regularizers",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if... | Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to modules inside modules) that must satisfy the same cons... | [
"Checks",
"the",
"given",
"regularizers",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L222-L260 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _is_scope_prefix | def _is_scope_prefix(scope_name, prefix_name):
"""Checks that `prefix_name` is a proper scope prefix of `scope_name`."""
if not prefix_name:
return True
if not scope_name.endswith("/"):
scope_name += "/"
if not prefix_name.endswith("/"):
prefix_name += "/"
return scope_name.startswith(prefix_n... | python | def _is_scope_prefix(scope_name, prefix_name):
"""Checks that `prefix_name` is a proper scope prefix of `scope_name`."""
if not prefix_name:
return True
if not scope_name.endswith("/"):
scope_name += "/"
if not prefix_name.endswith("/"):
prefix_name += "/"
return scope_name.startswith(prefix_n... | [
"def",
"_is_scope_prefix",
"(",
"scope_name",
",",
"prefix_name",
")",
":",
"if",
"not",
"prefix_name",
":",
"return",
"True",
"if",
"not",
"scope_name",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"scope_name",
"+=",
"\"/\"",
"if",
"not",
"prefix_name",
".",
... | Checks that `prefix_name` is a proper scope prefix of `scope_name`. | [
"Checks",
"that",
"prefix_name",
"is",
"a",
"proper",
"scope",
"prefix",
"of",
"scope_name",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L263-L275 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _get_sliced_variables | def _get_sliced_variables(var_list):
"""Separates the sliced (partitioned) and unsliced variables in var_list.
Args:
var_list: a list of variables.
Returns:
A list of unsliced variables in var_list, and a dict mapping names to parts
for the sliced variables in var_list.
"""
unsliced_variables = ... | python | def _get_sliced_variables(var_list):
"""Separates the sliced (partitioned) and unsliced variables in var_list.
Args:
var_list: a list of variables.
Returns:
A list of unsliced variables in var_list, and a dict mapping names to parts
for the sliced variables in var_list.
"""
unsliced_variables = ... | [
"def",
"_get_sliced_variables",
"(",
"var_list",
")",
":",
"unsliced_variables",
"=",
"[",
"]",
"sliced_variables",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"for",
"var",
"in",
"var_list",
":",
"if",
"var",
".",
"_save_slice... | Separates the sliced (partitioned) and unsliced variables in var_list.
Args:
var_list: a list of variables.
Returns:
A list of unsliced variables in var_list, and a dict mapping names to parts
for the sliced variables in var_list. | [
"Separates",
"the",
"sliced",
"(",
"partitioned",
")",
"and",
"unsliced",
"variables",
"in",
"var_list",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L279-L296 | train |
deepmind/sonnet | sonnet/python/modules/util.py | custom_getter_router | def custom_getter_router(custom_getter_map, name_fn):
"""Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispat... | python | def custom_getter_router(custom_getter_map, name_fn):
"""Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispat... | [
"def",
"custom_getter_router",
"(",
"custom_getter_map",
",",
"name_fn",
")",
":",
"for",
"custom_getter",
"in",
"custom_getter_map",
".",
"values",
"(",
")",
":",
"if",
"not",
"callable",
"(",
"custom_getter",
")",
":",
"raise",
"TypeError",
"(",
"\"Given custo... | Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispatches calls based on pattern matching the
name of the requ... | [
"Creates",
"a",
"custom",
"getter",
"than",
"matches",
"requests",
"to",
"dict",
"of",
"custom",
"getters",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L300-L368 | train |
deepmind/sonnet | sonnet/python/modules/util.py | get_normalized_variable_map | def get_normalized_variable_map(scope_or_module,
collection=tf.GraphKeys.GLOBAL_VARIABLES,
context=None,
group_sliced_variables=True):
"""Builds map of `tf.Variable`s in scope or module with normalized names.
The names ... | python | def get_normalized_variable_map(scope_or_module,
collection=tf.GraphKeys.GLOBAL_VARIABLES,
context=None,
group_sliced_variables=True):
"""Builds map of `tf.Variable`s in scope or module with normalized names.
The names ... | [
"def",
"get_normalized_variable_map",
"(",
"scope_or_module",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"GLOBAL_VARIABLES",
",",
"context",
"=",
"None",
",",
"group_sliced_variables",
"=",
"True",
")",
":",
"scope_name",
"=",
"get_variable_scope_name",
"(... | Builds map of `tf.Variable`s in scope or module with normalized names.
The names of the variables are normalized to remove the scope prefix.
Args:
scope_or_module: Scope or module to build map from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.GLOBAL_VARIABLES`, wh... | [
"Builds",
"map",
"of",
"tf",
".",
"Variable",
"s",
"in",
"scope",
"or",
"module",
"with",
"normalized",
"names",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L371-L425 | train |
deepmind/sonnet | sonnet/python/modules/util.py | get_saver | def get_saver(scope, collections=(tf.GraphKeys.GLOBAL_VARIABLES,), # pylint: disable=redefined-outer-name
context=None, **kwargs):
"""Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same... | python | def get_saver(scope, collections=(tf.GraphKeys.GLOBAL_VARIABLES,), # pylint: disable=redefined-outer-name
context=None, **kwargs):
"""Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same... | [
"def",
"get_saver",
"(",
"scope",
",",
"collections",
"=",
"(",
"tf",
".",
"GraphKeys",
".",
"GLOBAL_VARIABLES",
",",
")",
",",
"# pylint: disable=redefined-outer-name",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"variable_map",
"=",
"{",
"}"... | Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same variables to be restored into another similar scope or
module using a complementary `tf.train.Saver` object.
Args:
scope: Scope or module. Va... | [
"Builds",
"a",
"tf",
".",
"train",
".",
"Saver",
"for",
"the",
"scope",
"or",
"module",
"with",
"normalized",
"names",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L428-L453 | train |
deepmind/sonnet | sonnet/python/modules/util.py | variable_map_items | def variable_map_items(variable_map):
"""Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Y... | python | def variable_map_items(variable_map):
"""Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Y... | [
"def",
"variable_map_items",
"(",
"variable_map",
")",
":",
"for",
"key",
",",
"var_or_vars",
"in",
"six",
".",
"iteritems",
"(",
"variable_map",
")",
":",
"if",
"isinstance",
"(",
"var_or_vars",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"var... | Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Yields:
(string, tf.Variable) pairs. | [
"Yields",
"an",
"iterator",
"over",
"(",
"string",
"variable",
")",
"pairs",
"in",
"the",
"variable",
"map",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L471-L488 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _get_vars_to_collections | def _get_vars_to_collections(variables):
"""Returns a dict mapping variables to the collections they appear in."""
var_to_collections = collections.defaultdict(lambda: [])
if isinstance(variables, dict):
variables = list(v for _, v in variable_map_items(variables))
for graph in set(v.graph for v in variable... | python | def _get_vars_to_collections(variables):
"""Returns a dict mapping variables to the collections they appear in."""
var_to_collections = collections.defaultdict(lambda: [])
if isinstance(variables, dict):
variables = list(v for _, v in variable_map_items(variables))
for graph in set(v.graph for v in variable... | [
"def",
"_get_vars_to_collections",
"(",
"variables",
")",
":",
"var_to_collections",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"if",
"isinstance",
"(",
"variables",
",",
"dict",
")",
":",
"variables",
"=",
"list",
"(",
"v",
... | Returns a dict mapping variables to the collections they appear in. | [
"Returns",
"a",
"dict",
"mapping",
"variables",
"to",
"the",
"collections",
"they",
"appear",
"in",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L491-L506 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _format_device | def _format_device(var):
"""Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
... | python | def _format_device(var):
"""Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
... | [
"def",
"_format_device",
"(",
"var",
")",
":",
"if",
"var",
".",
"dtype",
".",
"name",
".",
"endswith",
"(",
"\"_ref\"",
")",
":",
"resource_var_annotation",
"=",
"\"(legacy)\"",
"else",
":",
"resource_var_annotation",
"=",
"\"(resource)\"",
"if",
"var",
".",
... | Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
Args:
var: The Tensorflo... | [
"Returns",
"the",
"device",
"with",
"an",
"annotation",
"specifying",
"ResourceVariable",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L509-L531 | train |
deepmind/sonnet | sonnet/python/modules/util.py | format_variables | def format_variables(variables, join_lines=True):
"""Takes a collection of variables and formats it as a table."""
rows = []
rows.append(("Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variables)
for var in sorted(variables, key=lambda var: var.op.name):
... | python | def format_variables(variables, join_lines=True):
"""Takes a collection of variables and formats it as a table."""
rows = []
rows.append(("Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variables)
for var in sorted(variables, key=lambda var: var.op.name):
... | [
"def",
"format_variables",
"(",
"variables",
",",
"join_lines",
"=",
"True",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"(",
"\"Variable\"",
",",
"\"Shape\"",
",",
"\"Type\"",
",",
"\"Collections\"",
",",
"\"Device\"",
")",
")",
"var_to_c... | Takes a collection of variables and formats it as a table. | [
"Takes",
"a",
"collection",
"of",
"variables",
"and",
"formats",
"it",
"as",
"a",
"table",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L534-L547 | train |
deepmind/sonnet | sonnet/python/modules/util.py | format_variable_map | def format_variable_map(variable_map, join_lines=True):
"""Takes a key-to-variable map and formats it as a table."""
rows = []
rows.append(("Key", "Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variable_map)
sort_key = lambda item: (item[0], item[1].name)... | python | def format_variable_map(variable_map, join_lines=True):
"""Takes a key-to-variable map and formats it as a table."""
rows = []
rows.append(("Key", "Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variable_map)
sort_key = lambda item: (item[0], item[1].name)... | [
"def",
"format_variable_map",
"(",
"variable_map",
",",
"join_lines",
"=",
"True",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"(",
"\"Key\"",
",",
"\"Variable\"",
",",
"\"Shape\"",
",",
"\"Type\"",
",",
"\"Collections\"",
",",
"\"Device\"",... | Takes a key-to-variable map and formats it as a table. | [
"Takes",
"a",
"key",
"-",
"to",
"-",
"variable",
"map",
"and",
"formats",
"it",
"as",
"a",
"table",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L550-L562 | train |
deepmind/sonnet | sonnet/python/modules/util.py | log_variables | def log_variables(variables=None):
"""Logs variable information.
This function logs the name, shape, type, collections, and device for either
all variables or a given iterable of variables. In the "Device" columns,
the nature of the variable (legacy or resource (for ResourceVariables)) is
also specified in p... | python | def log_variables(variables=None):
"""Logs variable information.
This function logs the name, shape, type, collections, and device for either
all variables or a given iterable of variables. In the "Device" columns,
the nature of the variable (legacy or resource (for ResourceVariables)) is
also specified in p... | [
"def",
"log_variables",
"(",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"for",
"row",
"in",
"format_variables",
"(",
"v... | Logs variable information.
This function logs the name, shape, type, collections, and device for either
all variables or a given iterable of variables. In the "Device" columns,
the nature of the variable (legacy or resource (for ResourceVariables)) is
also specified in parenthesis.
Args:
variables: iter... | [
"Logs",
"variable",
"information",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L565-L580 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _num_bytes_to_human_readable | def _num_bytes_to_human_readable(num_bytes):
"""Returns human readable string of how much memory `num_bytes` fills."""
if num_bytes < (2 ** 10):
return "%d B" % num_bytes
elif num_bytes < (2 ** 20):
return "%.3f KB" % (float(num_bytes) / (2 ** 10))
elif num_bytes < (2 ** 30):
return "%.3f MB" % (flo... | python | def _num_bytes_to_human_readable(num_bytes):
"""Returns human readable string of how much memory `num_bytes` fills."""
if num_bytes < (2 ** 10):
return "%d B" % num_bytes
elif num_bytes < (2 ** 20):
return "%.3f KB" % (float(num_bytes) / (2 ** 10))
elif num_bytes < (2 ** 30):
return "%.3f MB" % (flo... | [
"def",
"_num_bytes_to_human_readable",
"(",
"num_bytes",
")",
":",
"if",
"num_bytes",
"<",
"(",
"2",
"**",
"10",
")",
":",
"return",
"\"%d B\"",
"%",
"num_bytes",
"elif",
"num_bytes",
"<",
"(",
"2",
"**",
"20",
")",
":",
"return",
"\"%.3f KB\"",
"%",
"("... | Returns human readable string of how much memory `num_bytes` fills. | [
"Returns",
"human",
"readable",
"string",
"of",
"how",
"much",
"memory",
"num_bytes",
"fills",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L583-L592 | train |
deepmind/sonnet | sonnet/python/modules/util.py | summarize_variables | def summarize_variables(variables=None):
"""Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage ... | python | def summarize_variables(variables=None):
"""Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage ... | [
"def",
"summarize_variables",
"(",
"variables",
"=",
"None",
")",
":",
"variable_counts",
"=",
"count_variables_by_type",
"(",
"variables",
"=",
"variables",
")",
"total_num_scalars",
"=",
"0",
"total_num_bytes",
"=",
"0",
"# Sort by string representation of type name, so... | Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage cannot be accurately
calculated from the Gra... | [
"Logs",
"a",
"summary",
"of",
"variable",
"information",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L595-L627 | train |
deepmind/sonnet | sonnet/python/modules/util.py | count_variables_by_type | def count_variables_by_type(variables=None):
"""Returns a dict mapping dtypes to number of variables and scalars.
Args:
variables: iterable of `tf.Variable`s, or None. If None is passed, then all
global and local variables in the current graph are used.
Returns:
A dict mapping tf.dtype keys to a d... | python | def count_variables_by_type(variables=None):
"""Returns a dict mapping dtypes to number of variables and scalars.
Args:
variables: iterable of `tf.Variable`s, or None. If None is passed, then all
global and local variables in the current graph are used.
Returns:
A dict mapping tf.dtype keys to a d... | [
"def",
"count_variables_by_type",
"(",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"unique_types",
"=",
"set",
"(",
"v",
... | Returns a dict mapping dtypes to number of variables and scalars.
Args:
variables: iterable of `tf.Variable`s, or None. If None is passed, then all
global and local variables in the current graph are used.
Returns:
A dict mapping tf.dtype keys to a dict containing the keys 'num_scalars' and
'n... | [
"Returns",
"a",
"dict",
"mapping",
"dtypes",
"to",
"number",
"of",
"variables",
"and",
"scalars",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L630-L657 | train |
deepmind/sonnet | sonnet/python/modules/util.py | reuse_variables | def reuse_variables(method):
"""Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
... | python | def reuse_variables(method):
"""Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
... | [
"def",
"reuse_variables",
"(",
"method",
")",
":",
"initialized_variable_scopes_eager",
"=",
"set",
"(",
")",
"initialized_variable_scopes_graph",
"=",
"weakref",
".",
"WeakKeyDictionary",
"(",
")",
"# Ensure that the argument passed in is really a method by checking that the",
... | Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
value of an `_enter_variable_scop... | [
"Wraps",
"an",
"arbitrary",
"method",
"so",
"it",
"does",
"variable",
"sharing",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L660-L878 | train |
deepmind/sonnet | sonnet/python/modules/util.py | name_for_callable | def name_for_callable(func):
"""Returns a module name for a callable or `None` if no name can be found."""
if isinstance(func, functools.partial):
return name_for_callable(func.func)
try:
name = func.__name__
except AttributeError:
return None
if name == "<lambda>":
return None
else:
r... | python | def name_for_callable(func):
"""Returns a module name for a callable or `None` if no name can be found."""
if isinstance(func, functools.partial):
return name_for_callable(func.func)
try:
name = func.__name__
except AttributeError:
return None
if name == "<lambda>":
return None
else:
r... | [
"def",
"name_for_callable",
"(",
"func",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"functools",
".",
"partial",
")",
":",
"return",
"name_for_callable",
"(",
"func",
".",
"func",
")",
"try",
":",
"name",
"=",
"func",
".",
"__name__",
"except",
"Att... | Returns a module name for a callable or `None` if no name can be found. | [
"Returns",
"a",
"module",
"name",
"for",
"a",
"callable",
"or",
"None",
"if",
"no",
"name",
"can",
"be",
"found",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L881-L894 | train |
deepmind/sonnet | sonnet/python/modules/util.py | to_snake_case | def to_snake_case(camel_case):
"""Returns a CamelCase string as a snake_case string."""
if not re.match(r"^[A-Za-z_]\w*$", camel_case):
raise ValueError(
"Input string %s is not a valid Python identifier." % camel_case)
# Add underscore at word start and ends.
underscored = re.sub(r"([A-Z][a-z])", ... | python | def to_snake_case(camel_case):
"""Returns a CamelCase string as a snake_case string."""
if not re.match(r"^[A-Za-z_]\w*$", camel_case):
raise ValueError(
"Input string %s is not a valid Python identifier." % camel_case)
# Add underscore at word start and ends.
underscored = re.sub(r"([A-Z][a-z])", ... | [
"def",
"to_snake_case",
"(",
"camel_case",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r\"^[A-Za-z_]\\w*$\"",
",",
"camel_case",
")",
":",
"raise",
"ValueError",
"(",
"\"Input string %s is not a valid Python identifier.\"",
"%",
"camel_case",
")",
"# Add undersco... | Returns a CamelCase string as a snake_case string. | [
"Returns",
"a",
"CamelCase",
"string",
"as",
"a",
"snake_case",
"string",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L897-L909 | train |
deepmind/sonnet | sonnet/python/modules/util.py | notify_about_new_variables | def notify_about_new_variables(callback):
"""Calls `callback(var)` for all newly created variables.
Callback should not modify the variable passed in. Use cases that require
variables to be modified should use `variable_creator_scope` directly and sit
within the variable creator stack.
>>> variables = []
... | python | def notify_about_new_variables(callback):
"""Calls `callback(var)` for all newly created variables.
Callback should not modify the variable passed in. Use cases that require
variables to be modified should use `variable_creator_scope` directly and sit
within the variable creator stack.
>>> variables = []
... | [
"def",
"notify_about_new_variables",
"(",
"callback",
")",
":",
"def",
"_tracking_creator",
"(",
"getter",
",",
"*",
"*",
"kwargs",
")",
":",
"v",
"=",
"getter",
"(",
"*",
"*",
"kwargs",
")",
"callback",
"(",
"v",
")",
"return",
"v",
"with",
"tf",
".",... | Calls `callback(var)` for all newly created variables.
Callback should not modify the variable passed in. Use cases that require
variables to be modified should use `variable_creator_scope` directly and sit
within the variable creator stack.
>>> variables = []
>>> with notify_about_variables(variables.appen... | [
"Calls",
"callback",
"(",
"var",
")",
"for",
"all",
"newly",
"created",
"variables",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L941-L966 | train |
deepmind/sonnet | sonnet/python/modules/util.py | _recursive_getattr | def _recursive_getattr(module, path):
"""Recursively gets attributes inside `module` as specified by `path`."""
if "." not in path:
return getattr(module, path)
else:
first, rest = path.split(".", 1)
return _recursive_getattr(getattr(module, first), rest) | python | def _recursive_getattr(module, path):
"""Recursively gets attributes inside `module` as specified by `path`."""
if "." not in path:
return getattr(module, path)
else:
first, rest = path.split(".", 1)
return _recursive_getattr(getattr(module, first), rest) | [
"def",
"_recursive_getattr",
"(",
"module",
",",
"path",
")",
":",
"if",
"\".\"",
"not",
"in",
"path",
":",
"return",
"getattr",
"(",
"module",
",",
"path",
")",
"else",
":",
"first",
",",
"rest",
"=",
"path",
".",
"split",
"(",
"\".\"",
",",
"1",
... | Recursively gets attributes inside `module` as specified by `path`. | [
"Recursively",
"gets",
"attributes",
"inside",
"module",
"as",
"specified",
"by",
"path",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L975-L981 | train |
deepmind/sonnet | sonnet/python/modules/util.py | parse_string_to_constructor | def parse_string_to_constructor(ctor_string):
"""Returns a callable which corresponds to the constructor string.
Various modules (eg, ConvNet2D) take constructor arguments which are
callables, indicating a submodule to build. These can be passed as
actual constructors, eg `snt.LayerNorm`, however that makes th... | python | def parse_string_to_constructor(ctor_string):
"""Returns a callable which corresponds to the constructor string.
Various modules (eg, ConvNet2D) take constructor arguments which are
callables, indicating a submodule to build. These can be passed as
actual constructors, eg `snt.LayerNorm`, however that makes th... | [
"def",
"parse_string_to_constructor",
"(",
"ctor_string",
")",
":",
"orig_ctor_string",
"=",
"ctor_string",
"if",
"\".\"",
"not",
"in",
"ctor_string",
":",
"# No module specified - assume part of Sonnet",
"ctor_string",
"=",
"\"sonnet.\"",
"+",
"ctor_string",
"if",
"ctor_... | Returns a callable which corresponds to the constructor string.
Various modules (eg, ConvNet2D) take constructor arguments which are
callables, indicating a submodule to build. These can be passed as
actual constructors, eg `snt.LayerNorm`, however that makes the config
for that module not trivially serializab... | [
"Returns",
"a",
"callable",
"which",
"corresponds",
"to",
"the",
"constructor",
"string",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L984-L1024 | train |
deepmind/sonnet | sonnet/python/modules/util.py | supports_kwargs | def supports_kwargs(module_or_fn, kwargs_list):
"""Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of ... | python | def supports_kwargs(module_or_fn, kwargs_list):
"""Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of ... | [
"def",
"supports_kwargs",
"(",
"module_or_fn",
",",
"kwargs_list",
")",
":",
"if",
"isinstance",
"(",
"kwargs_list",
",",
"six",
".",
"string_types",
")",
":",
"kwargs_list",
"=",
"[",
"kwargs_list",
"]",
"# If it's not a function or method, then assume it's a module, s... | Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of underlying state, this function
introspects the mod... | [
"Determines",
"whether",
"the",
"provided",
"callable",
"supports",
"all",
"the",
"kwargs",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L1039-L1099 | train |
deepmind/sonnet | sonnet/python/modules/util.py | remove_unsupported_kwargs | def remove_unsupported_kwargs(module_or_fn, all_kwargs_dict):
"""Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.
A new dict is return with shallow copies of keys & values from
`all_kwargs_dict`, as long as the key is accepted by module_or_fn. The
returned dict can then be used to con... | python | def remove_unsupported_kwargs(module_or_fn, all_kwargs_dict):
"""Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.
A new dict is return with shallow copies of keys & values from
`all_kwargs_dict`, as long as the key is accepted by module_or_fn. The
returned dict can then be used to con... | [
"def",
"remove_unsupported_kwargs",
"(",
"module_or_fn",
",",
"all_kwargs_dict",
")",
":",
"if",
"all_kwargs_dict",
"is",
"None",
":",
"all_kwargs_dict",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"all_kwargs_dict",
",",
"dict",
")",
":",
"raise",
"ValueErro... | Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.
A new dict is return with shallow copies of keys & values from
`all_kwargs_dict`, as long as the key is accepted by module_or_fn. The
returned dict can then be used to connect `module_or_fn` (along with some
other inputs, ie non-keyword... | [
"Removes",
"any",
"kwargs",
"not",
"supported",
"by",
"module_or_fn",
"from",
"all_kwargs_dict",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L1102-L1137 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | merge_leading_dims | def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... | python | def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... | [
"def",
"merge_leading_dims",
"(",
"array_or_tensor",
",",
"n_dims",
"=",
"2",
")",
":",
"tensor",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"array_or_tensor",
")",
"tensor_shape_static",
"=",
"tensor",
".",
"get_shape",
"(",
")",
"# Check if the rank of the input te... | Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of dimensions to merge.
Returns:
Either the input val... | [
"Merge",
"the",
"first",
"dimensions",
"of",
"a",
"tensor",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L38-L89 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | split_leading_dim | def split_leading_dim(tensor, inputs, n_dims=2):
"""Split the first dimension of a tensor.
Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.
Returns:
The input tensor, with its first dimensio... | python | def split_leading_dim(tensor, inputs, n_dims=2):
"""Split the first dimension of a tensor.
Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.
Returns:
The input tensor, with its first dimensio... | [
"def",
"split_leading_dim",
"(",
"tensor",
",",
"inputs",
",",
"n_dims",
"=",
"2",
")",
":",
"input_shape_static",
"=",
"inputs",
".",
"get_shape",
"(",
")",
"input_shape_list",
"=",
"input_shape_static",
".",
"as_list",
"(",
")",
"tensor_shape_static",
"=",
"... | Split the first dimension of a tensor.
Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.
Returns:
The input tensor, with its first dimension split. | [
"Split",
"the",
"first",
"dimension",
"of",
"a",
"tensor",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L92-L120 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | create_linear_initializer | def create_linear_initializer(input_size, dtype=tf.float32):
"""Returns a default initializer for weights of a linear module."""
stddev = 1 / math.sqrt(input_size)
return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype) | python | def create_linear_initializer(input_size, dtype=tf.float32):
"""Returns a default initializer for weights of a linear module."""
stddev = 1 / math.sqrt(input_size)
return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype) | [
"def",
"create_linear_initializer",
"(",
"input_size",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"stddev",
"=",
"1",
"/",
"math",
".",
"sqrt",
"(",
"input_size",
")",
"return",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"stddev",... | Returns a default initializer for weights of a linear module. | [
"Returns",
"a",
"default",
"initializer",
"for",
"weights",
"of",
"a",
"linear",
"module",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L123-L126 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | calculate_bias_shape | def calculate_bias_shape(input_shape, bias_dims):
"""Calculate `bias_shape` based on the `input_shape` and `bias_dims`.
Args:
input_shape: Shape of the input being passed into the module. The leading
dimension is the minibatch size.
bias_dims: The dimensions that bias should be applied over. The re... | python | def calculate_bias_shape(input_shape, bias_dims):
"""Calculate `bias_shape` based on the `input_shape` and `bias_dims`.
Args:
input_shape: Shape of the input being passed into the module. The leading
dimension is the minibatch size.
bias_dims: The dimensions that bias should be applied over. The re... | [
"def",
"calculate_bias_shape",
"(",
"input_shape",
",",
"bias_dims",
")",
":",
"input_rank",
"=",
"len",
"(",
"input_shape",
")",
"# If None, default is to use all dimensions.",
"if",
"bias_dims",
"is",
"None",
":",
"return",
"input_shape",
"[",
"1",
":",
"]",
"# ... | Calculate `bias_shape` based on the `input_shape` and `bias_dims`.
Args:
input_shape: Shape of the input being passed into the module. The leading
dimension is the minibatch size.
bias_dims: The dimensions that bias should be applied over. The remaining
dimensions will get broadcasted over.
... | [
"Calculate",
"bias_shape",
"based",
"on",
"the",
"input_shape",
"and",
"bias_dims",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L464-L502 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | Linear._build | def _build(self, inputs):
"""Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the m... | python | def _build(self, inputs):
"""Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the m... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"input_shape",
"=",
"tuple",
"(",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
")",
"if",
"len",
"(",
"input_shape",
")",
"!=",
"2",
":",
"raise",
"base",
".",
"IncompatibleSha... | Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the multiplication. The
batch size... | [
"Connects",
"the",
"Linear",
"module",
"into",
"the",
"graph",
"with",
"input",
"Tensor",
"inputs",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L197-L265 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | Linear.output_size | def output_size(self):
"""Returns the module output size."""
if callable(self._output_size):
self._output_size = self._output_size()
return self._output_size | python | def output_size(self):
"""Returns the module output size."""
if callable(self._output_size):
self._output_size = self._output_size()
return self._output_size | [
"def",
"output_size",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"_output_size",
")",
":",
"self",
".",
"_output_size",
"=",
"self",
".",
"_output_size",
"(",
")",
"return",
"self",
".",
"_output_size"
] | Returns the module output size. | [
"Returns",
"the",
"module",
"output",
"size",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L300-L304 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | Linear.clone | def clone(self, name=None):
"""Returns a cloned `Linear` module.
Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.
Returns:
Cloned `Linear` module.
"""
if name is None:
name = self.m... | python | def clone(self, name=None):
"""Returns a cloned `Linear` module.
Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.
Returns:
Cloned `Linear` module.
"""
if name is None:
name = self.m... | [
"def",
"clone",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_clone\"",
"return",
"Linear",
"(",
"output_size",
"=",
"self",
".",
"output_size",
",",
"use_bias",
"=",... | Returns a cloned `Linear` module.
Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.
Returns:
Cloned `Linear` module. | [
"Returns",
"a",
"cloned",
"Linear",
"module",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L326-L343 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | ConcatLinear._build | def _build(self, inputs_list):
"""Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for... | python | def _build(self, inputs_list):
"""Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for... | [
"def",
"_build",
"(",
"self",
",",
"inputs_list",
")",
":",
"outputs",
"=",
"[",
"]",
"for",
"idx",
",",
"tensor",
"in",
"enumerate",
"(",
"inputs_list",
")",
":",
"outputs",
".",
"append",
"(",
"Linear",
"(",
"self",
".",
"_output_size",
",",
"initial... | Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for the multiplication. The batch size ma... | [
"Connects",
"the",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L436-L461 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | AddBias._build | def _build(self, inputs, multiplier=1):
"""Connects the Add module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of size `[batch_size, input_size1, ...]`.
multiplier: A scalar or Tensor which the bias term is multiplied by
before adding it to `inputs`. Anything which wo... | python | def _build(self, inputs, multiplier=1):
"""Connects the Add module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of size `[batch_size, input_size1, ...]`.
multiplier: A scalar or Tensor which the bias term is multiplied by
before adding it to `inputs`. Anything which wo... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
",",
"multiplier",
"=",
"1",
")",
":",
"input_shape",
"=",
"tuple",
"(",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
")",
"bias_shape",
"=",
"calculate_bias_shape",
"(",
"input_shape",
",",... | Connects the Add module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of size `[batch_size, input_size1, ...]`.
multiplier: A scalar or Tensor which the bias term is multiplied by
before adding it to `inputs`. Anything which works in the expression
`bias * multiplie... | [
"Connects",
"the",
"Add",
"module",
"into",
"the",
"graph",
"with",
"input",
"Tensor",
"inputs",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L603-L672 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | AddBias.transpose | def transpose(self, name=None):
"""Returns transposed `AddBias` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.
Returns:
Transposed `AddBias` module.
"""
if name is None:... | python | def transpose(self, name=None):
"""Returns transposed `AddBias` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.
Returns:
Transposed `AddBias` module.
"""
if name is None:... | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_transpose\"",
"return",
"AddBias",
"(",
"output_shape",
"=",
"lambda",
":",
"self",
".",
"_input_shape... | Returns transposed `AddBias` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.
Returns:
Transposed `AddBias` module. | [
"Returns",
"transposed",
"AddBias",
"module",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L696-L713 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | BatchReshape._infer_shape | def _infer_shape(self, dimensions):
"""Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input dimensions.
Args:
dimensions: List of input non-batch dimensions.
Returns:
Tuple of non-batch output dimensions.
"""
# Size of ... | python | def _infer_shape(self, dimensions):
"""Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input dimensions.
Args:
dimensions: List of input non-batch dimensions.
Returns:
Tuple of non-batch output dimensions.
"""
# Size of ... | [
"def",
"_infer_shape",
"(",
"self",
",",
"dimensions",
")",
":",
"# Size of input",
"n",
"=",
"np",
".",
"prod",
"(",
"dimensions",
")",
"# Size of output where defined",
"m",
"=",
"np",
".",
"prod",
"(",
"abs",
"(",
"np",
".",
"array",
"(",
"self",
".",... | Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input dimensions.
Args:
dimensions: List of input non-batch dimensions.
Returns:
Tuple of non-batch output dimensions. | [
"Replaces",
"the",
"-",
"1",
"wildcard",
"in",
"the",
"output",
"shape",
"vector",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L759-L777 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | BatchReshape._build | def _build(self, inputs):
"""Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_preserve_dims+1, ...].
Returns:
A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
... | python | def _build(self, inputs):
"""Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_preserve_dims+1, ...].
Returns:
A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"full_input_shape",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"len",
"(",
"full_input_shape",
")",
"<",
"self",
".",
"_preserve_dims",
":",
"raise",
"ValueError",
"("... | Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_preserve_dims+1, ...].
Returns:
A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_reshape_1, b_reshape_2, ... | [
"Connects",
"the",
"module",
"into",
"the",
"graph",
"with",
"input",
"Tensor",
"inputs",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L779-L860 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | BatchReshape.transpose | def transpose(self, name=None):
"""Returns transpose batch reshape."""
if name is None:
name = self.module_name + "_transpose"
return BatchReshape(shape=lambda: self.input_shape,
preserve_dims=self._preserve_dims,
name=name) | python | def transpose(self, name=None):
"""Returns transpose batch reshape."""
if name is None:
name = self.module_name + "_transpose"
return BatchReshape(shape=lambda: self.input_shape,
preserve_dims=self._preserve_dims,
name=name) | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_transpose\"",
"return",
"BatchReshape",
"(",
"shape",
"=",
"lambda",
":",
"self",
".",
"input_shape",
... | Returns transpose batch reshape. | [
"Returns",
"transpose",
"batch",
"reshape",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L868-L874 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | TrainableVariable._build | def _build(self):
"""Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor.
"""
if "w" not in self._initializers:
stddev = 1 / math.sqrt(np.prod(self._shape))
self._initializers["w"] = tf.truncated_normal_initializer(stddev=std... | python | def _build(self):
"""Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor.
"""
if "w" not in self._initializers:
stddev = 1 / math.sqrt(np.prod(self._shape))
self._initializers["w"] = tf.truncated_normal_initializer(stddev=std... | [
"def",
"_build",
"(",
"self",
")",
":",
"if",
"\"w\"",
"not",
"in",
"self",
".",
"_initializers",
":",
"stddev",
"=",
"1",
"/",
"math",
".",
"sqrt",
"(",
"np",
".",
"prod",
"(",
"self",
".",
"_shape",
")",
")",
"self",
".",
"_initializers",
"[",
... | Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor. | [
"Connects",
"the",
"TrainableTensor",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L983-L999 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | BatchApply._build | def _build(self, *args, **kwargs):
"""Connects the BatchApply module into the graph.
Args:
*args: a Tensor or a nested list or dictionary of Tensors. The input
tensors will have their first dimensions merged, then an op or a
module will be called on the input. The first dimension of t... | python | def _build(self, *args, **kwargs):
"""Connects the BatchApply module into the graph.
Args:
*args: a Tensor or a nested list or dictionary of Tensors. The input
tensors will have their first dimensions merged, then an op or a
module will be called on the input. The first dimension of t... | [
"def",
"_build",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"flattened",
"=",
"nest",
".",
"flatten",
"(",
"[",
"args",
",",
"kwargs",
"]",
")",
"merged_flattened",
"=",
"[",
"merge_leading_dims",
"(",
"inp",
",",
"self",
".",
... | Connects the BatchApply module into the graph.
Args:
*args: a Tensor or a nested list or dictionary of Tensors. The input
tensors will have their first dimensions merged, then an op or a
module will be called on the input. The first dimension of the output
tensor(s) will be spli... | [
"Connects",
"the",
"BatchApply",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1063-L1100 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | SliceByDim._build | def _build(self, inputs):
"""Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `input... | python | def _build(self, inputs):
"""Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `input... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"shape_inputs",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"rank",
"=",
"len",
"(",
"shape_inputs",
")",
"# Checks that the rank of the tensor.",
"max_dim",
"=",
"np",
".",
"m... | Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `inputs` tensor has insufficient rank. | [
"Connects",
"the",
"SliceByDim",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1167-L1197 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | TileByDim._build | def _build(self, inputs):
"""Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor.
"""
shape_inputs = inputs.get_shape().as_list()
rank = len(shape_inputs)
# Builds default lists for multiples to pass to `tf.tile`.
full_... | python | def _build(self, inputs):
"""Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor.
"""
shape_inputs = inputs.get_shape().as_list()
rank = len(shape_inputs)
# Builds default lists for multiples to pass to `tf.tile`.
full_... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"shape_inputs",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"rank",
"=",
"len",
"(",
"shape_inputs",
")",
"# Builds default lists for multiples to pass to `tf.tile`.",
"full_multiples"... | Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor. | [
"Connects",
"the",
"TileByDim",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1252-L1271 | train |
deepmind/sonnet | sonnet/python/modules/basic.py | MergeDims._build | def _build(self, inputs):
"""Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueErr... | python | def _build(self, inputs):
"""Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueErr... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"if",
"nest",
".",
"is_sequence",
"(",
"inputs",
")",
":",
"merged_tensors",
"=",
"[",
"self",
".",
"_merge",
"(",
"tensor",
")",
"for",
"tensor",
"in",
"nest",
".",
"flatten",
"(",
"inputs",
")"... | Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueError: If any of the `inputs` tensor... | [
"Connects",
"the",
"MergeDims",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1354-L1372 | train |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | RelationalMemory.initial_state | def initial_state(self, batch_size, trainable=False):
"""Creates the initial memory.
We should ensure each row of the memory is initialized to be unique,
so initialize the matrix to be the identity. We then pad or truncate
as necessary so that init_state is of size
(batch_size, self._mem_slots, sel... | python | def initial_state(self, batch_size, trainable=False):
"""Creates the initial memory.
We should ensure each row of the memory is initialized to be unique,
so initialize the matrix to be the identity. We then pad or truncate
as necessary so that init_state is of size
(batch_size, self._mem_slots, sel... | [
"def",
"initial_state",
"(",
"self",
",",
"batch_size",
",",
"trainable",
"=",
"False",
")",
":",
"init_state",
"=",
"tf",
".",
"eye",
"(",
"self",
".",
"_mem_slots",
",",
"batch_shape",
"=",
"[",
"batch_size",
"]",
")",
"# Pad the matrix with zeros.",
"if",... | Creates the initial memory.
We should ensure each row of the memory is initialized to be unique,
so initialize the matrix to be the identity. We then pad or truncate
as necessary so that init_state is of size
(batch_size, self._mem_slots, self._mem_size).
Args:
batch_size: The size of the ba... | [
"Creates",
"the",
"initial",
"memory",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L92-L118 | train |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | RelationalMemory._multihead_attention | def _multihead_attention(self, memory):
"""Perform multi-head attention from 'Attention is All You Need'.
Implementation of the attention mechanism from
https://arxiv.org/abs/1706.03762.
Args:
memory: Memory tensor to perform attention on.
Returns:
new_memory: New memory tensor.
"... | python | def _multihead_attention(self, memory):
"""Perform multi-head attention from 'Attention is All You Need'.
Implementation of the attention mechanism from
https://arxiv.org/abs/1706.03762.
Args:
memory: Memory tensor to perform attention on.
Returns:
new_memory: New memory tensor.
"... | [
"def",
"_multihead_attention",
"(",
"self",
",",
"memory",
")",
":",
"key_size",
"=",
"self",
".",
"_key_size",
"value_size",
"=",
"self",
".",
"_head_size",
"qkv_size",
"=",
"2",
"*",
"key_size",
"+",
"value_size",
"total_size",
"=",
"qkv_size",
"*",
"self"... | Perform multi-head attention from 'Attention is All You Need'.
Implementation of the attention mechanism from
https://arxiv.org/abs/1706.03762.
Args:
memory: Memory tensor to perform attention on.
Returns:
new_memory: New memory tensor. | [
"Perform",
"multi",
"-",
"head",
"attention",
"from",
"Attention",
"is",
"All",
"You",
"Need",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L120-L161 | train |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | RelationalMemory._create_gates | def _create_gates(self, inputs, memory):
"""Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate.
"""
# We... | python | def _create_gates(self, inputs, memory):
"""Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate.
"""
# We... | [
"def",
"_create_gates",
"(",
"self",
",",
"inputs",
",",
"memory",
")",
":",
"# We'll create the input and forget gates at once. Hence, calculate double",
"# the gate size.",
"num_gates",
"=",
"2",
"*",
"self",
".",
"_calculate_gate_size",
"(",
")",
"memory",
"=",
"tf",... | Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate. | [
"Create",
"input",
"and",
"forget",
"gates",
"for",
"this",
"step",
"using",
"inputs",
"and",
"memory",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L184-L210 | train |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | RelationalMemory._attend_over_memory | def _attend_over_memory(self, memory):
"""Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory.
"""
attention_mlp = basic.BatchApply(
mlp.MLP([self._mem_size] * self._attention_mlp_layers))
for _ in range(se... | python | def _attend_over_memory(self, memory):
"""Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory.
"""
attention_mlp = basic.BatchApply(
mlp.MLP([self._mem_size] * self._attention_mlp_layers))
for _ in range(se... | [
"def",
"_attend_over_memory",
"(",
"self",
",",
"memory",
")",
":",
"attention_mlp",
"=",
"basic",
".",
"BatchApply",
"(",
"mlp",
".",
"MLP",
"(",
"[",
"self",
".",
"_mem_size",
"]",
"*",
"self",
".",
"_attention_mlp_layers",
")",
")",
"for",
"_",
"in",
... | Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory. | [
"Perform",
"multiheaded",
"attention",
"over",
"memory",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L212-L234 | train |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | RelationalMemory._build | def _build(self, inputs, memory, treat_input_as_matrix=False):
"""Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Default... | python | def _build(self, inputs, memory, treat_input_as_matrix=False):
"""Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Default... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
",",
"memory",
",",
"treat_input_as_matrix",
"=",
"False",
")",
":",
"if",
"treat_input_as_matrix",
":",
"inputs",
"=",
"basic",
".",
"BatchFlatten",
"(",
"preserve_dims",
"=",
"2",
")",
"(",
"inputs",
")",
"inp... | Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Defaulta to False, in which case the input is flattened
into a vector... | [
"Adds",
"relational",
"memory",
"to",
"the",
"TensorFlow",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L236-L272 | train |
deepmind/sonnet | sonnet/examples/mnist_mlp.py | train_and_eval | def train_and_eval(train_batch_size, test_batch_size, num_hidden, learning_rate,
num_train_steps, report_every, test_every):
"""Creates a basic MNIST model using Sonnet, then trains and evaluates it."""
data_dict = dataset_mnist.get_data("mnist", train_batch_size, test_batch_size)
train_data =... | python | def train_and_eval(train_batch_size, test_batch_size, num_hidden, learning_rate,
num_train_steps, report_every, test_every):
"""Creates a basic MNIST model using Sonnet, then trains and evaluates it."""
data_dict = dataset_mnist.get_data("mnist", train_batch_size, test_batch_size)
train_data =... | [
"def",
"train_and_eval",
"(",
"train_batch_size",
",",
"test_batch_size",
",",
"num_hidden",
",",
"learning_rate",
",",
"num_train_steps",
",",
"report_every",
",",
"test_every",
")",
":",
"data_dict",
"=",
"dataset_mnist",
".",
"get_data",
"(",
"\"mnist\"",
",",
... | Creates a basic MNIST model using Sonnet, then trains and evaluates it. | [
"Creates",
"a",
"basic",
"MNIST",
"model",
"using",
"Sonnet",
"then",
"trains",
"and",
"evaluates",
"it",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/mnist_mlp.py#L43-L96 | train |
deepmind/sonnet | sonnet/python/modules/rnn_core.py | _single_learnable_state | def _single_learnable_state(state, state_id=0, learnable=True):
"""Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
... | python | def _single_learnable_state(state, state_id=0, learnable=True):
"""Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
... | [
"def",
"_single_learnable_state",
"(",
"state",
",",
"state_id",
"=",
"0",
",",
"learnable",
"=",
"True",
")",
":",
"unpacked_state",
"=",
"tf",
".",
"unstack",
"(",
"state",
")",
"# Assert that all rows have the same values.",
"assert_rows_equal",
"=",
"[",
"tf",... | Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
state: initial value of the initial state. It should be a tensor o... | [
"Returns",
"an",
"initial",
"(",
"maybe",
"learnable",
")",
"state",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L44-L89 | train |
deepmind/sonnet | sonnet/python/modules/rnn_core.py | trainable_initial_state | def trainable_initial_state(batch_size, state_size, dtype, initializers=None,
regularizers=None, name=None):
"""Creates an initial state consisting of trainable variables.
The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce... | python | def trainable_initial_state(batch_size, state_size, dtype, initializers=None,
regularizers=None, name=None):
"""Creates an initial state consisting of trainable variables.
The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce... | [
"def",
"trainable_initial_state",
"(",
"batch_size",
",",
"state_size",
",",
"dtype",
",",
"initializers",
"=",
"None",
",",
"regularizers",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"flat_state_size",
"=",
"nest",
".",
"flatten",
"(",
"state_size",
"... | Creates an initial state consisting of trainable variables.
The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce an initial state.
Args:
batch_size: An int, or scalar int32 Tensor representing the batch size.
state_size: A `TensorShape` or nes... | [
"Creates",
"an",
"initial",
"state",
"consisting",
"of",
"trainable",
"variables",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L92-L167 | train |
deepmind/sonnet | sonnet/python/modules/rnn_core.py | with_doc | def with_doc(fn_with_doc_to_copy):
"""Returns a decorator to copy documentation from the given function.
Docstring is copied, including *args and **kwargs documentation.
Args:
fn_with_doc_to_copy: Function whose docstring, including *args and
**kwargs documentation, is to be copied.
Returns:
De... | python | def with_doc(fn_with_doc_to_copy):
"""Returns a decorator to copy documentation from the given function.
Docstring is copied, including *args and **kwargs documentation.
Args:
fn_with_doc_to_copy: Function whose docstring, including *args and
**kwargs documentation, is to be copied.
Returns:
De... | [
"def",
"with_doc",
"(",
"fn_with_doc_to_copy",
")",
":",
"def",
"decorator",
"(",
"wrapper_init",
")",
":",
"# Wrap the target class's constructor (to assume its docstring),",
"# but invoke the wrapper class's constructor.",
"@",
"wrapt",
".",
"decorator",
"def",
"wrapping_fn",... | Returns a decorator to copy documentation from the given function.
Docstring is copied, including *args and **kwargs documentation.
Args:
fn_with_doc_to_copy: Function whose docstring, including *args and
**kwargs documentation, is to be copied.
Returns:
Decorated version of `wrapper_init` with d... | [
"Returns",
"a",
"decorator",
"to",
"copy",
"documentation",
"from",
"the",
"given",
"function",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L385-L407 | train |
deepmind/sonnet | sonnet/python/modules/rnn_core.py | TrainableInitialState._build | def _build(self):
"""Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor.
"""
flat_initial_state = nest.flatten(self._initial_state)
if self._mask is not None:
flat_mask = n... | python | def _build(self):
"""Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor.
"""
flat_initial_state = nest.flatten(self._initial_state)
if self._mask is not None:
flat_mask = n... | [
"def",
"_build",
"(",
"self",
")",
":",
"flat_initial_state",
"=",
"nest",
".",
"flatten",
"(",
"self",
".",
"_initial_state",
")",
"if",
"self",
".",
"_mask",
"is",
"not",
"None",
":",
"flat_mask",
"=",
"nest",
".",
"flatten",
"(",
"self",
".",
"_mask... | Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor. | [
"Connects",
"the",
"module",
"to",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L331-L349 | train |
deepmind/sonnet | sonnet/python/modules/layer_norm.py | LayerNorm._build | def _build(self, inputs):
"""Connects the LayerNorm module into the graph.
Args:
inputs: a Tensor of dimensionality >= 2.
Returns:
normalized: layer normalized outputs with same shape as inputs.
Raises:
base.NotSupportedError: If `inputs` has less than 2 dimensions.
"""
if ... | python | def _build(self, inputs):
"""Connects the LayerNorm module into the graph.
Args:
inputs: a Tensor of dimensionality >= 2.
Returns:
normalized: layer normalized outputs with same shape as inputs.
Raises:
base.NotSupportedError: If `inputs` has less than 2 dimensions.
"""
if ... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"if",
"self",
".",
"_axis",
"is",
"None",
":",
"axis",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"inputs",
".",
"shape",
".",
"ndims",
")",
")",
"else",
":",
"axis",
"=",
"self",
".",
"_axi... | Connects the LayerNorm module into the graph.
Args:
inputs: a Tensor of dimensionality >= 2.
Returns:
normalized: layer normalized outputs with same shape as inputs.
Raises:
base.NotSupportedError: If `inputs` has less than 2 dimensions. | [
"Connects",
"the",
"LayerNorm",
"module",
"into",
"the",
"graph",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/layer_norm.py#L115-L179 | train |
deepmind/sonnet | sonnet/python/modules/attention.py | AttentiveRead._build | def _build(self, memory, query, memory_mask=None):
"""Perform a differentiable read.
Args:
memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of
dtype float32. This represents, for each example and memory slot, a
single embedding to attend over.
query: [batch_size, qu... | python | def _build(self, memory, query, memory_mask=None):
"""Perform a differentiable read.
Args:
memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of
dtype float32. This represents, for each example and memory slot, a
single embedding to attend over.
query: [batch_size, qu... | [
"def",
"_build",
"(",
"self",
",",
"memory",
",",
"query",
",",
"memory_mask",
"=",
"None",
")",
":",
"if",
"len",
"(",
"memory",
".",
"get_shape",
"(",
")",
")",
"!=",
"3",
":",
"raise",
"base",
".",
"IncompatibleShapeError",
"(",
"\"memory must have sh... | Perform a differentiable read.
Args:
memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of
dtype float32. This represents, for each example and memory slot, a
single embedding to attend over.
query: [batch_size, query_word_size]-shaped Tensor of dtype float32.
Rep... | [
"Perform",
"a",
"differentiable",
"read",
"."
] | 00612ca3178964d86b556e062694d808ff81fcca | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/attention.py#L60-L183 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.