






'''simple docstring'''





import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


_UpperCamelCase						:						Optional[int]  =					logging.getLogger(__name__)
def __UpperCAmelCase   (					A					:			Optional[Any]			,       A					:			Optional[Any]		)    ->   Tuple:
			# save results
			if os.path.exists(A		):
						if os.path.exists(os.path.join(A			,       '''config.json'''		)		) and os.path.isfile(
						    os.path.join(A			,       '''config.json'''		)		):
									os.remove(os.path.join(A			,       '''config.json'''		)		)
						if os.path.exists(os.path.join(A			,       '''pytorch_model.bin'''		)		) and os.path.isfile(
						    os.path.join(A			,       '''pytorch_model.bin'''		)		):
									os.remove(os.path.join(A			,       '''pytorch_model.bin'''		)		)
			else:
						os.makedirs(A		)
			model.save_pretrained(A		)
def __UpperCAmelCase   (					A					:			List[str]			,       A					:			Union[str, Any]=False		)    ->   str:
			UpperCAmelCase_      :       List[str]          =       2
			if unlogit:
						UpperCAmelCase_      :       List[Any]          =       torch.pow(A			,       A		)
			UpperCAmelCase_      :       Dict          =       p * torch.log(A		)
			UpperCAmelCase_      :       List[Any]          =       0
			return -plogp.sum(dim=-1		)
def __UpperCAmelCase   (					A					:			List[Any]		)    ->   Dict:
			logger.info('''lv, h >\t''' + '''\t'''.join(F"{x + 1}" for x in range(len(A		)		)		)		)
			for row in range(len(A		)		):
						if tensor.dtype != torch.long:
									logger.info(F"layer {row + 1}:\t" + '''\t'''.join(F"{x:.5f}" for x in tensor[row].cpu().data		)		)
						else:
									logger.info(F"layer {row + 1}:\t" + '''\t'''.join(F"{x:d}" for x in tensor[row].cpu().data		)		)
def __UpperCAmelCase   (					A					:			Any			,       A					:			Optional[Any]			,       A					:			List[Any]			,       A					:			str=True			,       A					:			str=True			,       A					:			Union[str, Any]=None			,       A					:			Dict=False		)    ->   Tuple:
			UpperCAmelCase_    ,      UpperCAmelCase_      :       Any          =       model.config.num_hidden_layers, model.config.num_attention_heads
			UpperCAmelCase_      :       Optional[Any]          =       torch.zeros(A			,       A		).to(args.device		)
			UpperCAmelCase_      :       Tuple          =       torch.zeros(A			,       A		).to(args.device		)

			if head_mask is None:
						UpperCAmelCase_      :       Optional[int]          =       torch.ones(A			,       A		).to(args.device		)

			head_mask.requires_grad_(requires_grad=A		)
			# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
			if actually_pruned:
						UpperCAmelCase_      :       str          =       None

			UpperCAmelCase_      :       str          =       0.0
			UpperCAmelCase_      :       Any          =       0.0
			for step, inputs in enumerate(tqdm(A			,       desc='''Iteration'''			,       disable=args.local_rank not in [-1, 0]		)		):
						UpperCAmelCase_      :       List[str]          =       tuple(t.to(args.device		) for t in inputs		)
						((UpperCAmelCase_)    ,      )      :       int          =       inputs

						# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
						UpperCAmelCase_      :       List[Any]          =       model(A			,       labels=A			,       head_mask=A		)
						#  (loss), lm_logits, presents, (all hidden_states), (attentions)
						UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       List[str]          =       (
						    outputs[0],
						    outputs[1],
						    outputs[-1],
						)  # Loss and logits are the first, attention the last
						loss.backward()  # Backpropagate to populate the gradients in the head mask
						total_loss += loss.detach().cpu().numpy()
						if compute_entropy:
									for layer, attn in enumerate(A		):
												UpperCAmelCase_      :       int          =       entropy(attn.detach()			,       A		)
												attn_entropy[layer] += masked_entropy.sum(-1		).sum(0		).sum(0		).detach()

						if compute_importance:
									head_importance += head_mask.grad.abs().detach()
						tot_tokens += torch.ones_like(A		).float().detach().sum().data

			# Normalize
			attn_entropy /= tot_tokens
			head_importance /= tot_tokens
			# Layerwise importance normalization
			if not args.dont_normalize_importance_by_layer:
						UpperCAmelCase_      :       Any          =       2
						UpperCAmelCase_      :       Dict          =       torch.pow(torch.pow(A			,       A		).sum(-1		)			,       1 / exponent		)
						head_importance /= norm_by_layer.unsqueeze(-1		) + 1e-20

			if not args.dont_normalize_global_importance:
						UpperCAmelCase_      :       Union[str, Any]          =       (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

			# Print matrices
			if compute_entropy:
						logger.info('''Attention entropies'''		)
						print_ad_tensor(A		)
			if compute_importance:
						logger.info('''Head importance scores'''		)
						print_ad_tensor(A		)
			logger.info('''Head ranked by importance scores'''		)
			UpperCAmelCase_      :       str          =       torch.zeros(head_importance.numel()			,       dtype=torch.long			,       device=args.device		)
			UpperCAmelCase_      :       Optional[int]          =       torch.arange(
			    head_importance.numel()			,       device=args.device		)
			UpperCAmelCase_      :       Optional[Any]          =       head_ranks.view_as(A		)
			print_ad_tensor(A		)
			return attn_entropy, head_importance, total_loss
def __UpperCAmelCase   (					A					:			Optional[Any]			,       A					:			Optional[int]			,       A					:			List[str]		)    ->   Dict:
			UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       List[Any]          =       compute_heads_importance(A			,       A			,       A			,       compute_entropy=A		)
			UpperCAmelCase_      :       int          =       1 / loss  # instead of downsteam score use the LM loss
			logger.info('''Pruning: original score: %f, threshold: %f'''			,       A			,       original_score * args.masking_threshold		)

			UpperCAmelCase_      :       List[str]          =       torch.ones_like(A		)
			UpperCAmelCase_      :       int          =       max(1			,       int(new_head_mask.numel() * args.masking_amount		)		)

			UpperCAmelCase_      :       Dict          =       original_score
			while current_score >= original_score * args.masking_threshold:
						UpperCAmelCase_      :       Any          =       new_head_mask.clone().detach()  # save current head mask
						# heads from least important to most - keep only not-masked heads
						UpperCAmelCase_      :       Tuple          =       float('''Inf'''		)
						UpperCAmelCase_      :       Dict          =       head_importance.view(-1		).sort()[1]

						if len(A		) <= num_to_mask:
									print('''BREAK BY num_to_mask'''		)
									break

						# mask heads
						UpperCAmelCase_      :       List[str]          =       current_heads_to_mask[:num_to_mask]
						logger.info('''Heads to mask: %s'''			,       str(current_heads_to_mask.tolist()		)		)
						UpperCAmelCase_      :       Tuple          =       new_head_mask.view(-1		)
						UpperCAmelCase_      :       str          =       0.0
						UpperCAmelCase_      :       Any          =       new_head_mask.view_as(A		)
						UpperCAmelCase_      :       List[str]          =       new_head_mask.clone().detach()
						print_ad_tensor(A		)

						# Compute metric and head importance again
						UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       Dict          =       compute_heads_importance(
						    A			,       A			,       A			,       compute_entropy=A			,       head_mask=A		)
						UpperCAmelCase_      :       Tuple          =       1 / loss
						logger.info(
						    '''Masking: current score: %f, remaining heads %d (%.1f percents)'''			,       A			,       new_head_mask.sum()			,       new_head_mask.sum() / new_head_mask.numel() * 1_0_0			,       )

			logger.info('''Final head mask'''		)
			print_ad_tensor(A		)
			np.save(os.path.join(args.output_dir			,       '''head_mask.npy'''		)			,       head_mask.detach().cpu().numpy()		)

			return head_mask
def __UpperCAmelCase   (					A					:			int			,       A					:			Any			,       A					:			str			,       A					:			Any		)    ->   Any:
			UpperCAmelCase_      :       Optional[Any]          =       datetime.now()
			UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       List[Any]          =       compute_heads_importance(
			    A			,       A			,       A			,       compute_entropy=A			,       compute_importance=A			,       head_mask=A		)
			UpperCAmelCase_      :       Any          =       1 / loss
			UpperCAmelCase_      :       Union[str, Any]          =       datetime.now() - before_time

			UpperCAmelCase_      :       Any          =       sum(p.numel() for p in model.parameters()		)
			UpperCAmelCase_      :       int          =       {
			    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(A		)		)
			}

			for k, v in heads_to_prune.items():
						if isinstance(A			,       A		):
									UpperCAmelCase_      :       Dict          =       [
									    v,
									]

			assert sum(len(A		) for h in heads_to_prune.values()		) == (1 - head_mask.long()).sum().item()
			model.prune_heads(A		)
			UpperCAmelCase_      :       List[Any]          =       sum(p.numel() for p in model.parameters()		)

			UpperCAmelCase_      :       Any          =       datetime.now()
			UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       List[Any]          =       compute_heads_importance(
			    A			,       A			,       A			,       compute_entropy=A			,       compute_importance=A			,       head_mask=A			,       actually_pruned=A			,       )

			UpperCAmelCase_      :       Optional[int]          =       1 / loss
			UpperCAmelCase_      :       Any          =       datetime.now() - before_time

			logger.info(
			    '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'''			,       A			,       A			,       pruned_num_params / original_num_params * 1_0_0			,       )
			logger.info('''Pruning: score with masking: %f score with pruning: %f'''			,       A			,       A		)
			logger.info('''Pruning: speed ratio (original timing / new timing): %f percents'''			,       original_time / new_time * 1_0_0		)
			save_model(A			,       args.output_dir		)
def __UpperCAmelCase   (					)    ->   Dict:
			UpperCAmelCase_      :       List[str]          =       argparse.ArgumentParser()
			# Required parameters
			parser.add_argument(
			    '''--data_dir'''			,       default=A			,       type=A			,       required=A			,       help='''The input data dir. Should contain the .tsv files (or other data files) for the task.'''			,       )
			parser.add_argument(
			    '''--model_name_or_path'''			,       default=A			,       type=A			,       required=A			,       help='''Path to pretrained model or model identifier from huggingface.co/models'''			,       )
			parser.add_argument(
			    '''--output_dir'''			,       default=A			,       type=A			,       required=A			,       help='''The output directory where the model predictions and checkpoints will be written.'''			,       )

			# Other parameters
			parser.add_argument(
			    '''--config_name'''			,       default=''''''			,       type=A			,       help='''Pretrained config name or path if not the same as model_name_or_path'''			,       )
			parser.add_argument(
			    '''--tokenizer_name'''			,       default=''''''			,       type=A			,       help='''Pretrained tokenizer name or path if not the same as model_name_or_path'''			,       )
			parser.add_argument(
			    '''--cache_dir'''			,       default=A			,       type=A			,       help='''Where do you want to store the pre-trained models downloaded from s3'''			,       )
			parser.add_argument(
			    '''--data_subset'''			,       type=A			,       default=-1			,       help='''If > 0: limit the data to a subset of data_subset instances.'''		)
			parser.add_argument(
			    '''--overwrite_output_dir'''			,       action='''store_true'''			,       help='''Whether to overwrite data in output directory'''		)
			parser.add_argument(
			    '''--overwrite_cache'''			,       action='''store_true'''			,       help='''Overwrite the cached training and evaluation sets'''		)

			parser.add_argument(
			    '''--dont_normalize_importance_by_layer'''			,       action='''store_true'''			,       help='''Don\'t normalize importance score by layers'''		)
			parser.add_argument(
			    '''--dont_normalize_global_importance'''			,       action='''store_true'''			,       help='''Don\'t normalize all importance scores between 0 and 1'''			,       )

			parser.add_argument(
			    '''--try_masking'''			,       action='''store_true'''			,       help='''Whether to try to mask head until a threshold of accuracy.'''		)
			parser.add_argument(
			    '''--masking_threshold'''			,       default=0.9			,       type=A			,       help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'''			,       )
			parser.add_argument(
			    '''--masking_amount'''			,       default=0.1			,       type=A			,       help='''Amount to heads to masking at each masking step.'''		)
			parser.add_argument('''--metric_name'''			,       default='''acc'''			,       type=A			,       help='''Metric to use for head masking.'''		)

			parser.add_argument(
			    '''--max_seq_length'''			,       default=1_2_8			,       type=A			,       help=(
			        '''The maximum total input sequence length after WordPiece tokenization. \n'''
			        '''Sequences longer than this will be truncated, sequences shorter padded.'''
			    )			,       )
			parser.add_argument('''--batch_size'''			,       default=1			,       type=A			,       help='''Batch size.'''		)

			parser.add_argument('''--seed'''			,       type=A			,       default=4_2		)
			parser.add_argument('''--local_rank'''			,       type=A			,       default=-1			,       help='''local_rank for distributed training on gpus'''		)
			parser.add_argument('''--no_cuda'''			,       action='''store_true'''			,       help='''Whether not to use CUDA when available'''		)
			parser.add_argument('''--server_ip'''			,       type=A			,       default=''''''			,       help='''Can be used for distant debugging.'''		)
			parser.add_argument('''--server_port'''			,       type=A			,       default=''''''			,       help='''Can be used for distant debugging.'''		)
			UpperCAmelCase_      :       Tuple          =       parser.parse_args()

			if args.server_ip and args.server_port:
						# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
						import ptvsd

						print('''Waiting for debugger attach'''		)
						ptvsd.enable_attach(address=(args.server_ip, args.server_port)			,       redirect_output=A		)
						ptvsd.wait_for_attach()

			# Setup devices and distributed training
			if args.local_rank == -1 or args.no_cuda:
						UpperCAmelCase_      :       str          =       torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''		)
						UpperCAmelCase_      :       Optional[Any]          =       0 if args.no_cuda else torch.cuda.device_count()
			else:
						torch.cuda.set_device(args.local_rank		)
						UpperCAmelCase_      :       Dict          =       torch.device('''cuda'''			,       args.local_rank		)
						UpperCAmelCase_      :       Optional[Any]          =       1
						torch.distributed.init_process_group(backend='''nccl'''		)  # Initializes the distributed backend

			# Setup logging
			logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN		)
			logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device			,       args.n_gpu			,       bool(args.local_rank != -1		)		)		)

			UpperCAmelCase_      :       List[Any]          =       GPTaLMHeadModel.from_pretrained(args.model_name_or_path		)

			# Distributed and parallel training
			model.to(args.device		)
			if args.local_rank != -1:
						UpperCAmelCase_      :       Tuple          =       nn.parallel.DistributedDataParallel(
						    A			,       device_ids=[args.local_rank]			,       output_device=args.local_rank			,       find_unused_parameters=A		)
			elif args.n_gpu > 1:
						UpperCAmelCase_      :       Optional[Any]          =       nn.DataParallel(A		)

			# Print/save training arguments
			os.makedirs(args.output_dir			,       exist_ok=A		)
			torch.save(A			,       os.path.join(args.output_dir			,       '''run_args.bin'''		)		)
			logger.info('''Training/evaluation parameters %s'''			,       A		)

			# Prepare dataset
			UpperCAmelCase_      :       Any          =       np.concatenate(
			    [
			        np.loadtxt(args.data_dir			,       dtype=np.intaa		),
			    ]		)
			UpperCAmelCase_      :       int          =       (torch.from_numpy(A		),)
			UpperCAmelCase_      :       int          =       TensorDataset(*A		)
			UpperCAmelCase_      :       List[str]          =       RandomSampler(A		)
			UpperCAmelCase_      :       List[str]          =       DataLoader(A			,       sampler=A			,       batch_size=args.batch_size		)

			# Compute head entropy and importance score
			compute_heads_importance(A			,       A			,       A		)

			# Try head masking (set heads to zero until the score goes under a threshole)
			# and head pruning (remove masked heads and see the effect on the network)
			if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
						UpperCAmelCase_      :       int          =       mask_heads(A			,       A			,       A		)
						prune_heads(A			,       A			,       A			,       A		)


if __name__ == "__main__":
						main()










'''simple docstring'''





from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


_UpperCamelCase						:						int  =					logging.get_logger(__name__)
def __UpperCAmelCase   (					A					:			Union[tf.Tensor, np.ndarray]		)    ->   List[int]:
			if isinstance(A			,       np.ndarray		):
						return list(tensor.shape		)

			UpperCAmelCase_      :       str          =       tf.shape(A		)

			if tensor.shape == tf.TensorShape(A		):
						return dynamic

			UpperCAmelCase_      :       Any          =       tensor.shape.as_list()

			return [dynamic[i] if s is None else s for i, s in enumerate(A		)]
def __UpperCAmelCase   (					A					:			tf.Tensor			,       A					:			Optional[int] = None			,       A					:			Optional[str] = None		)    ->   tf.Tensor:
			return tf.nn.softmax(logits=logits + 1e-9			,       axis=A			,       name=A		)
def __UpperCAmelCase   (					A					:			List[str]			,       A					:			Union[str, Any]			,       A					:			List[str]			,       A					:			str=1e-5			,       A					:			Dict=-1		)    ->   List[Any]:
			# This is a very simplified functional layernorm, designed to duplicate
			# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
			# models in Transformers.

			if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(A			,       A		):
						raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.'''		)

			# Get mean and variance on the axis to be normalized
			UpperCAmelCase_    ,      UpperCAmelCase_      :       int          =       tf.nn.moments(A			,       axes=[axis]			,       keepdims=A		)

			if axis != -1:
						# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
						# on every dimension except axis
						UpperCAmelCase_      :       Tuple          =       [1] * inputs.shape.rank
						UpperCAmelCase_      :       int          =       shape_list(A		)[axis]
						UpperCAmelCase_      :       Dict          =       tf.reshape(A			,       A		)
						UpperCAmelCase_      :       Optional[Any]          =       tf.reshape(A			,       A		)

			# Compute layer normalization using the batch_normalization
			# function.
			UpperCAmelCase_      :       Dict          =       tf.nn.batch_normalization(
			    A			,       A			,       A			,       offset=A			,       scale=A			,       variance_epsilon=A			,       )
			return outputs
def __UpperCAmelCase   (					A					:			Dict			,       A					:			int=0			,       A					:			Optional[int]=-1		)    ->   str:
			# Replicates the behavior of torch.flatten in TF

			# If end_dim or start_dim is negative, count them from the end
			if end_dim < 0:
						end_dim += input.shape.rank
			if start_dim < 0:
						start_dim += input.shape.rank

			if start_dim == end_dim:
						return input

			UpperCAmelCase_      :       Any          =       tf.shape(A		)
			UpperCAmelCase_      :       Dict          =       tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]		)
			UpperCAmelCase_      :       Optional[int]          =       tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]			,       axis=0		)
			return tf.reshape(A			,       A		)
def __UpperCAmelCase   (					A					:			tf.Tensor		)    ->   tf.Tensor:
			if not isinstance(A			,       tf.Tensor		):
						UpperCAmelCase_      :       Optional[Any]          =       tf.convert_to_tensor(A		)  # Catches stray NumPy inputs
			if encoder_attention_mask.shape.rank == 3:
						UpperCAmelCase_      :       Any          =       encoder_attention_mask[:, None, :, :]
			if encoder_attention_mask.shape.rank == 2:
						UpperCAmelCase_      :       Tuple          =       encoder_attention_mask[:, None, None, :]
			# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
			# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
			# /transformer/transformer_layers.py#L270
			# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
			# encoder_extended_attention_mask.transpose(-1, -2))
			UpperCAmelCase_      :       int          =       (
			    tf.cast(1			,       encoder_attention_mask.dtype		) - encoder_extended_attention_mask
			) * encoder_extended_attention_mask.dtype.min

			return encoder_extended_attention_mask
def __UpperCAmelCase   (					A					:			tf.Tensor			,       A					:			int			,       A					:			str = "input_ids"		)    ->   None:
			tf.debugging.assert_less(
			    A			,       tf.cast(A			,       dtype=tensor.dtype		)			,       message=(
			        F"The maximum value of {tensor_name} ({tf.math.reduce_max(A		)}) must be smaller than the embedding "
			        F"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
			    )			,       )
def __UpperCAmelCase   (					A					:			Dict			,       A					:			Tuple			,       A					:			List[str]		)    ->   Union[str, Any]:
			UpperCAmelCase_      :       List[Any]          =       6_4_5_1_2
			# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
			# because in that case even chunking the array would not make the saving
			# possible.
			UpperCAmelCase_      :       Tuple          =       [x for x in data if len(A		) > HDF5_OBJECT_HEADER_LIMIT]

			# Expecting this to never be true.
			if bad_attributes:
						raise RuntimeError(
						    '''The following attributes cannot be saved to HDF5 file because '''
						    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
						    F"bytes: {bad_attributes}"		)

			UpperCAmelCase_      :       Union[str, Any]          =       np.asarray(A		)

			UpperCAmelCase_      :       Optional[int]          =       1
			UpperCAmelCase_      :       str          =       np.array_split(A			,       A		)

			# This will never loop forever thanks to the test above.
			while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data		):
						num_chunks += 1
						UpperCAmelCase_      :       Dict          =       np.array_split(A			,       A		)

			if num_chunks > 1:
						for chunk_id, chunk_data in enumerate(A		):
									UpperCAmelCase_      :       int          =       chunk_data
			else:
						UpperCAmelCase_      :       List[Any]          =       data
def __UpperCAmelCase   (					A					:			int			,       A					:			Optional[Any]		)    ->   Tuple:
			if name in group.attrs:
						UpperCAmelCase_      :       Optional[int]          =       [n.decode('''utf8'''		) if hasattr(A			,       '''decode'''		) else n for n in group.attrs[name]]
			else:
						UpperCAmelCase_      :       Optional[int]          =       []
						UpperCAmelCase_      :       Optional[int]          =       0
						while "%s%d" % (name, chunk_id) in group.attrs:
									data.extend(
									    [n.decode('''utf8'''		) if hasattr(A			,       '''decode'''		) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]]		)
									chunk_id += 1
			return data







def __UpperCAmelCase   (					A					:			Tuple		)    ->   str:

			def _expand_single_ad_tensor(A					:			int		):
						if isinstance(A			,       tf.Tensor		) and t.shape.rank == 1:
									return tf.expand_dims(A			,       axis=-1		)
						return t

			return tf.nest.map_structure(_expand_single_ad_tensor			,       A		)


